<?php
/**
 * Author: yixuan
 * Desc:
 * Time: 2016/6/8 14:26
 */

namespace app\mobile\controller;

use app\lib\WxoffiAccount;
use app\model\Ad;
use app\model\Comm;
use app\model\Util;
use app\model\Complain;
use app\model\Fans;
use app\model\Game;
use app\model\Koi;
use app\model\Order;
use app\model\Pay;
use app\model\Poster;
use app\model\Record;
use app\model\Theme;
use app\model\Worker;
use app\model\Yxgifts;
use app\model\Userdata;
use app\model\W_init;
use app\model\W_input;
use app\plugin\core\inc\PluginRoute;
use think\Db;
use think\Session;
use app\model\Sms;
use app\model\Recordbase;
use app\model\Relation;
use app\model\Otherform;
use app\model\Common;

class Entry extends Base
{


    //获取宝箱礼品
    public function GetBoxGift()
    {
        global $_P, $_G;
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $config = Theme::getConfig($themeid);
        if ($system['isboxgift'] == 1) {
            //取出所有配置项
            $fans = Fans::getById($_G['member']['uid'], $themeid);
            if (!empty($fans['address'])) {
                $result = Ad::getFansBoxGift($config, $fans['address']);
            }
            if (empty($result)) {
                $result = Ad::getAddressGift($themeid, 'get');
                db_query("UPDATE " . tablename(t_fans) . " SET address = '" . $result['name'] . "' WHERE themeid = '" . $themeid . "' and uid = '" . $_G['member']['uid'] . "'");
            }

            if (!empty($result)) {
                $result['errcode'] = 0;
            } else {
                $result = array(
                    'errcode' => 1,
                    'msg' => ' 参数配置错误'
                );
            }
        } else {
            $result = array(
                'errcode' => 1,
                'msg' => '未开启此功能'
            );
        }
        return return_msg($result, '', 'ajax');
    }

    public function Excel()
    {
        global $_G, $_S, $_C, $_P;
        $logo = $_G['companylogo'];
        $op = $_P['op'];
        $secret_key = $_P['secret_key'];
        $themeid = $_P['themeid'];
        $code = 200;
        $msg = '下载成功';
        $refresh = 1;
        $excel = db_get('excel', ['secret_key' => $secret_key]);
//        if ($excel && $excel['open_num']<1){
//            $op = 'download';
//
//        }else{
//            $op ='show_page';
//        }
        $referer_url = $_COOKIE['download_excel_referer_url'];

        if ($op == 'show_page') {
            db_update('excel', ['open_num' => $excel['open_num'] + 1], ['secret_key' => $secret_key]);

            $return_clicent = get_defined_vars();
            return view('base/excel', $return_clicent);
        }

        if ($op == 'download') {
            $refresh = 2;
            $excel = db_get('excel', ['secret_key' => $secret_key, 'effective_time >' => time()]);
            $return_clicent = get_defined_vars();
            if (empty($excel)) {
                $code = 201;
                $msg = '未找到文件';
                $return_clicent = get_defined_vars();
                return view('base/excel', $return_clicent);
            }
            if (time() > $excel['effective_time']) {
                $code = 201;
                $msg = '文件已过期';
                $return_clicent = get_defined_vars();
                return view('base/excel', $return_clicent);
            }
            $html = urldecode($excel['excel']);

            $file_name = substr($excel['header2'], strripos($excel['header2'], "=") + 1);
            $encoded_filename = urlencode($file_name);
            $encoded_filename = str_replace("+", "%20", $encoded_filename);
            header('Content-Encoding: UTF-8');
            header($excel['header1'] . "; charset=UTF-8");
            ob_end_clean();
            header('Cache-Control: max-age=0');
            if (preg_match("/MSIE/", $_SERVER["HTTP_USER_AGENT"]) || preg_match("/Trident\/7.0/", $_SERVER["HTTP_USER_AGENT"])) {
                header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
            } else if (preg_match("/Safari/", $_SERVER["HTTP_USER_AGENT"])) {
                header('Content-Disposition: attachment; filename*=utf-8\'\'' . rawurlencode($file_name));
            } else {
                header("Content-Disposition: attachment;filename=\"$file_name\"");
            }

            echo $html;
            exit();
        }
    }

    public function Dopay()
    {
        global $_P, $_G;
        $system = $_G['system'];
        if ($system['pn_wxapp'] > 0) {
            echo "<script src='https://res.wx.qq.com/open/js/jweixin-1.3.2.js'></script>";
            echo "<script language='javascript' type='text/javascript'>";
            echo "var ua = navigator.userAgent.toLowerCase();";
            echo "if(ua.match(/MicroMessenger/i)=='micromessenger') {";
            echo "    wx.miniProgram.getEnv((res)=>{";
            echo "        if (res.miniprogram) {";
            echo "            wx.miniProgram.navigateTo({";
            echo "                url: `/h5/pages/pay/pay`";
            echo "            });";
            echo "        }";
            echo "    })";
            echo "}";
            echo "</script>";
            exit;
        }
        $params = array('isrecharge' => false);
        $ordertype = 'theme';
        $_G['member']['uid'] = Fans::getRealUid();
        if (empty($_G['openid']) || empty($_G['member']['uid'])) {
            return return_msg($_G['openid'] . '授权失败，请重启手机重试！' . $_G['member']['uid']);
            return;
        }
        $orderid = intval($_P['orderid']);
        $order = Order::getByIdAndOpenid($orderid, $_G['openid']);
        if (empty($order)) {
            return return_msg('记录不存在，请重新下单');
        }
        if ($order['status'] != 0) {
            return return_msg('定单已完成支付');
        }
        if ($order['orderfee'] <= 0) {
            return return_msg('定单金额必须大于0元');
        }

        $desclen = 26;
        $theme = Theme::getThemeById($order['themeid']);
        if (!empty($theme['mobile'])) {
            $desc = "【客服" . $theme['mobile'] . "】";
            $desclen = $desclen - mb_strlen($desc);
        }
        if (!empty($theme['jubf'])) {
            $desc = mb_substr($theme['jubf'], 0, $desclen, "UTF-8") . $desc;
        } else {
            $desc = mb_substr($theme['title'], 0, $desclen, "UTF-8") . $desc;
        }
        $title = $desc;

        //判断是否为易宣公众号
        $softid = substr(MODULE_NAME, -5);
        $serverconfigs = Db::name('00serverconfig')->where('id', 'neq', 0)->find();
        $serverconfig = !empty($serverconfigs['settings']) ? xunserializer($serverconfigs['settings']) : [];
        if (DOMAIN1 != 'www.yixuan.net' && $softid % 10 == 1 && !empty($serverconfig['mchid2'])) {
            //判断易宣放行
        } else {
            //检测平台表商户信息与system商户信息是否一致
            $check_platform_item = Db::table('yx_sys_platform')->where(['id' => $_G['mpid']])->find();
            if ($check_platform_item && $check_platform_item['mchid'] && $check_platform_item['apikey']) {
                //获取system商户信息
                if ($system && $system['mchid'] && $system['apikey']) {
                    if ($check_platform_item['mchid'] != $system['mchid']) {
                        return return_msg('-1参数设置商户信息与平台设置信息不一致');
                    }
                }
            }
        }


        if ($system['send_mode'] == 1) {
            $params ['profit_sharing'] = 'Y';
        }
        $params ['themeid'] = $order['themeid'];
        $params ['uniontid'] = $order['uniontid'];
        $params ['tid'] = $order['tid'];
        $params ['user'] = $_G['openid'];
        $params ['uid'] = $_G['member']['uid'];
        $params ['fee'] = $order['orderfee'];
        $params ['title'] = $title;
        $params ['ordersn'] = $order['ordersn'];
        $params ['virtual'] = false;
        $params ['orderid'] = $order['id'];
        $this->helppay($params);
        $this->pay($params);
    }


    protected function helppay($params)
    {
        global $_G;
        $log = db_get('yx_sys_paylog', array('mpid' => $_G['mpid'], 'module' => MODULE_NAME, 'tid' => $params['tid']));
        //在pay方法中，要检测是否已经生成了paylog定单记录，如果没有需要插入一条定单数据
        //未调用系统pay方法的，可以将此代码放至自己的pay方法中，进行漏洞修复
        if (empty($log)) {
            $log = array(
                'mpid' => $_G['mpid'],
                'openid' => $_G['member']['openid'],
                'module' => MODULE_NAME, //模块名称，请保证$this可用
                'tid' => $params['tid'],
                'uniontid' => $params['uniontid'],
                'fee' => $params['fee'],
                'status' => '0',
            );
            db_insert('yx_sys_paylog', $log);
        }

    }

    protected function pay($params)
    {
        global $_G, $_P;
        if ($_G['app_web_wxapp'] != 'mobile') {
            return_msg('支付功能只能在手机上使用');
        }
        $params['module'] = $params['module_name'] = MODULE_NAME;
        if ($params['fee'] <= 0) {
            $format_pars = [];
            $format_pars['from'] = 'return';
            $format_pars['result'] = 'success';
            $format_pars['type'] = '';
            $format_pars['tid'] = $params['tid'];
            exit(Pay::payResult($format_pars));
        }
        $log = Db::table('yx_sys_paylog')->where(array('mpid' => $_G['mpid'], 'module' => $params['module'], 'tid' => $params['tid']))->find();
        if (empty($log)) {
            $log = [
                'mpid' => $_G['mpid'],
                'openid' => $_G['member']['openid'],
                'module' => MODULE_NAME,
                'tid' => $params['tid'],
                'uniontid' => $params['uniontid'],
                'fee' => $params['fee'],
                'status' => '0',
            ];
            $log['id'] = Db::table('yx_sys_paylog')->insertGetId($log);
        }
        if ($log['status'] == '1') {
            return_msg('这个订单已经支付成功, 不需要重复支付.', '', 'info');
        }
        $params['openid'] = $log['openid'];
        if (!empty($log['id'])) {
            $tag = [];
            $tag['mpid'] = $_G['mpid'];
            $tag['uid'] = $_G['member']['uid'];
            db_update('yx_sys_paylog', ['openid' => $_G['member']['openid'], 'tag' => xserializer($tag)], ['id' => $log['id']]);
        }
        $params['title'] = urlencode($params['title']);
        $sl = base64_encode(json_encode($params));
        $auth = sha1($sl . $_G['mpid'] . MODULE_NAME);
        //调用微信侧预订单生成
        $this->redirect('/payment/wechat/pay?sl=' . $sl . '&auth=' . $auth);
    }

    protected function transformCollection($items)
    {
        return array_map([$this, 'transform'], $items);
    }

    protected function transform($item)
    {
        // DOTO
        return $item;
    }


    //在线充值页
    public function W_recharge()
    {
        global $_P, $_G;
        $fans = $this->checkuser();
        if (empty($fans['uid']) || empty($_G['openid'])) {
            return return_msg('用户未授权无法访问，请从首页重新进入');
            exit;
        }
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $theme = Theme::getThemeById($themeid);

        if ($_P['op'] == 'pay') {
            $data = array(
                'uniacid' => $_G['mpid'],
                'ordertype' => 990,
                'themeid' => $themeid,
                'openid' => $_G['openid'],
                'uid' => $_G['member']['uid'],
                'username' => '后台充值',
                'status' => 0,
                'type' => 'wechat',
            );
            $data['orderfee'] = $_P['fee'];
            $data['masterid'] = 0;
            $data['detailid'] = 0;
            $billcode = getMillisecond();
            $tid = '0' . $billcode;
            $data['tid'] = $tid;
            $data['addtime'] = TIMESTAMP;
            $data['ordersn'] = $billcode;
            $orderid = Order::save($data);

            $result = array();
            $result['errcode'] = 0;
            $result['orderid'] = $orderid;
            $result['tid'] = $tid;
            $result['fee'] = $_P['fee'];
            $result['title'] = '活动款';
            $result['payway'] = 0;
            $result['url'] = $_G['siteroot'] . createMobileUrl('dopay', array('themeid' => $themeid, 'orderid' => $orderid));
            return return_msg($result, '', 'ajax');
        } else {
            $recharge = Comm::getRechargeFee($system, $theme, $themeid);
            $return_clicent = get_defined_vars();
            return view('fcworker/fc_recharge', $return_clicent);
        }
    }

    public function GetMyInfo()
    {

        global $_G, $_P;
        $fans = $this->checkuser();
        $system = $this->getsystem();
        $themeid = intval($_P['themeid']);
        $theme = Theme::getThemeById($themeid);
        $config = Theme::getConfig($themeid);
        $result = Record::getMyInfo($system, $theme, $config, $fans);
        return_json($result['error'], $result['msg'], $result['data']);
    }

//后台注册页面
    public function X_init()
    {

        global $_G, $_P;
        $fans = $this->checkuser();
        $system = $this->getsystem();
        $themeid = intval($_P['themeid']);
        $theme = Theme::getThemeById($themeid);
        $showpage = 1;
        if (empty($theme['id'])) {
            return return_msg('管理后台地址不正确');
            exit;
        }
        if (empty($theme['softsn'])) {
            return return_msg('软件未激活,请联系' . $_G['companyname'] . '工作人员');
        }
        $msg = Worker::isWorkerMax($system, $themeid);
        if (!empty($msg)) {
            return return_msg($msg);
        }
        $msg = Worker::gethoutaistats();
        if (!empty($msg)) {
            return return_msg($msg);
        }
        $config = Theme::getConfig($themeid);
        $wx = $_G['platform']['jssdkconfig'];

        if ($system['is_multiple_merchants']) {
            $shoplist = db_select("SELECT id,name FROM " . tablename(t_shangjia) .
                " WHERE  state = 1 order by displayorder");
        }
        $uploadurl = $_G['siteroot'] . createMobileUrl('X_init', array("op" => 'upload', "themeid" => $themeid, "soft" => $theme['softkey'], "server_openid" => $_P['server_openid']));
        if ($_P['op'] == 'upload') {
//            $r=downloadFromWxServer($system,$_P['bid']);
            $r = Util::YxUploadImg($_P);
            $r['remotepath'] = str_replace('http://', 'https://', $r['remotepath']);
            return return_msg($r, '', 'ajax');
            exit;

        }
        if (!empty($_P['pass']) && $config['workerpass_mode'] == '0') {
            $worker_count = (int)db_fetchcolumn("SELECT COUNT(*) FROM " . tablename(t_worker) .
                " WHERE themeid = " . $themeid);
            if ($worker_count > 0 || $system['is_multiple_merchants']) {
                $_SESSION['dest_url'] = urlencode($_G['url_full']);
                $autonext = true;
            }
        }
        $nopass_url = str_replace('pass', 'pa-ss', $_G['url_full']);
        if ($_P['op'] == 'next') {
            if (!$_G['ispost']) {
                die('非法请求');
                exit;
            }
            $showpage = 2;
            $result = W_Init::pass($system, $config);
            if ($result['error'] == 1) {
                return_json($result['error'], $result['msg']);
            } else {
                if ($result['data']['level'] == '3') {
                    $result = W_Init::getteamlist($system, $config, $result['data']['company']);
                    $result['data']['level'] = 3;
                    $showpage = 3;
                }
                $result['data']['showpage'] = $showpage;
                if ($result['error']) {
                    die($result['msg']);
                    exit;
                } else {
                    return_json($result['error'], $result['msg'], $result['data']);
                }

            }
        } elseif ($_P['op'] == 'last') {
            if (!$_G['ispost']) {
                die('非法请求');
                exit;
            }
            $wx = $_G['platform']['jssdkconfig'];
            $showpage = 3;
            W_Init::saveteam($system);
            $result = W_Init::getteamlist($system, $config);
            $result['data']['showpage'] = $showpage;
            if ($result['error']) {
                die($result['msg']);
                exit;
            } else {
                return_json($result['error'], $result['msg'], $result['data']);
            }
        } elseif ($_P['op'] == 'save') {
            if (!$_G['ispost']) {
                die('非法请求');
                exit;
            }
            $showpage = 9;
            $myworker = Worker::getThemeWorkerByOpenid($fans['openid'], $themeid, 0);
            $r = W_Init::saveinfo($system, $config, $theme, $fans, $themeid, $myworker, false);
            if ($r['error'] == 1) {
                return_json(1, $r['msg'], '');
            }
            $shenfen = '';
            $jubf['title'] = empty($theme['jubf']) ? '' : $theme['jubf'] . '-';
            $jubf['banquan'] = !empty($theme['USERCOMPANYNAME']) ? $theme['USERCOMPANYNAME'] : $_G['companyname'];

            $myworker = Worker::getThemeWorkerByOpenid($fans['openid'], $themeid, 1);
            if ($myworker) {
                if ($myworker['team'] > 0) {
                    $team = db_find("SELECT * FROM " . tablename(t_team) . " WHERE id= '{$myworker['team']}'");
                    $teamname = $team['name'];
                }
                $result['myworker'] = $myworker;
                if ($myworker['level'] == 1) {
                    $shenfen = '超级管理员';
                } elseif ($myworker['level'] == 2) {
                    $shenfen = '商家管理员';
                } else {
                    $shenfen = '员工';
                }
                $sharedata = array(
                    'themeid' => $themeid,
                    'fopenid' => $_G['openid'],
                    'fromuid' => $_G['member']['uid'],
                    'workerid' => $myworker['uid'],
                    'flag' => 1,
                );

                db_update(t_fans, array('poster' => ''), array('uid' => $_G['member']['uid']));

                if ($system['gongzhong'] == '1') {
                    $domaintxt = $system['domainhead1'];
                } else {
                    $domaintxt = DOMAIN0;
                }
                $workerurl = $_G['url_scheme'] . $domaintxt . "/" . createMobileUrl('index', $sharedata);
                $workerurl = Poster::GetWorkerUrl($system, $workerurl, MODULE_NAME . "员工:" . $myworker['username']);
                $img_url = QRURLNEW . urlencode($workerurl);
                if ($system['selling_agent'] == 1) {
                    $sharedata = array(
                        'themeid' => $themeid,
                        'superior' => $_G['member']['uid']
                    );
                    $w_init_agent_url = $_G['url_scheme'] . $domaintxt . "/" . createMobileUrl('w_init_agent', $sharedata);
                    $w_init_agent_url = Poster::GetWorkerUrl($system, $w_init_agent_url, MODULE_NAME . "注册代理:" . $myworker['username']);
                    $img_url = QRURLNEW . urlencode($w_init_agent_url);
                }

                $result['teamname'] = $teamname;
//                $result['shopname']=$shopname;
                $result['showpage'] = $showpage;
                $result['shenfen'] = $shenfen;
                $result['jubf'] = $jubf;

                $result['x_index'] = $_G['url_scheme'] . $domaintxt . "/" . createMobileUrl('x_index', $sharedata);
                $result['workerurl'] = $workerurl;
                $result['img_url'] = $img_url;

                if ($result['error']) {
                    die($result['msg']);
                    exit;
                } else {
                    return_json(0, '', $result);
                }
            } else {
                return_json(1, '注册失败，请重试', '');
            }
            $result = array();
        } else {
            Userdata::MyPath($themeid, 0, $_G['member']['uid'], 0);
            Userdata::addLog($themeid, $_G['member']['uid'], 1, '访问员工注册页');

            $jubf['title'] = empty($theme['jubf']) ? '' : $theme['jubf'] . '-';
            $jubf['banquan'] = !empty($theme['USERCOMPANYNAME']) ? $theme['USERCOMPANYNAME'] : $_G['companyname'];

            $shareinfo = Theme::getshareinfo($system, $theme, $config, $fans, '', '', 0);
            $result['shareinfo'] = $shareinfo;
            $result['jubf'] = $jubf;
            $result['islogin'] = empty($fans['avatar']) ? true : false;
            $result['jishu'] = Worker::getjishu($theme, $system);
            $result['shoplist'] = $shoplist;
            $result['ruanjian'] = $system['ruanjian'];
            $return_clicent = get_defined_vars();
            return view('fcworker/fc_init', $return_clicent);
        }


    }

//    后台测试样式修改
    public function X_index()
    {
        global $_P, $_G;
        $wx = $_G['platform']['jssdkconfig'];
        $main = 'x_index';
        $baseinfo = $this->Isworker();
        $theme = $baseinfo['theme'];
        $system = $baseinfo['system'];
        //客户UID数据库重复，自动修正
        $fans_error = db_select("SELECT uid FROM " . tablename(t_fans) . " where uid>0 and themeid='" . $_P['themeid'] . "' GROUP BY uid HAVING COUNT(*) > 1");
        if (!empty($fans_error)) {
            $fans_error = db_select("SELECT uid,openid,nickname,avatar FROM " . tablename('yx_sys_members') . "
                WHERE `openid` in (SELECT `openid`  FROM " . tablename(t_fans) . "
             where  uid IN (
              SELECT uid
              FROM " . tablename(t_fans) . "
              where uid >0 and themeid='" . $_P['themeid'] . "'
              GROUP BY uid
              HAVING COUNT(*) > 1
            ) and themeid='" . $_P['themeid'] . "')");
            if (!empty($fans_error)) {
                yxlog($fans_error, 'UID重复');
                db_updateall(t_scan, $fans_error, 'openid');
                db_updateall(t_friend, $fans_error, 'openid');
                db_updateall(t_relation, $fans_error, 'openid');
                db_updateall(t_fans, $fans_error, 'openid');
                db_updateall(t_worker, $fans_error, 'openid');
                db_updateall(t_record, $fans_error, 'openid');
                foreach ($fans_error as $key => $value) {
                    unset($fans_error[$key]['nickname']);
                    unset($fans_error[$key]['avatar']);
                }
                db_updateall(t_order, $fans_error, 'openid');
                db_updateall(t_comm, $fans_error, 'openid');
                db_updateall(t_commshare, $fans_error, 'openid');
            }
        }

        if ($system['h5work'] != 1) {
            $url = str_replace("x_index", "w_index", $_G['url_full']);
            echo "<script language='javascript' type='text/javascript'>";
            echo "window.location.href='$url';";
            echo "</script>";
            exit;
        }

        if ($baseinfo['fans']['nickname'] == '微信用户' || $baseinfo['fans']['nickname'] == '新用户') {
            $workerurl = Fans::get_login_url($system, $theme);
            //如果员工打开的链接为原始链接则先刷新
            echo "<script language='javascript' type='text/javascript'>";
            echo "window.location.href='$workerurl';";
            echo "</script>";
            exit;
        }


        $result = Fans::w_index($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        if ($result['error'] == 1) {
            return_json(1, $result['msg']);
        } else {
            $themeid = $baseinfo['theme']['id'];
            $level = $result['level'];
            $info = $result['info'];
            $config = $result['config'];
            $jishu = $baseinfo['jishu'];
            $jubf = $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            $company_name = $_G['companyname'];

            $lottery_info = [];
            if ($system['lottery'] == 1 && TIMESTAMP > $config['yx_lt_begintime']) {
                require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
                require_once get_path('plugin/lottery/core/model.php');
                $lottery_info = \LotteryModel::getPrizeFlagCount($baseinfo['theme']['id']);
                $total_Arr = array_column($lottery_info, 'total');
                array_multisort($total_Arr, SORT_DESC, $lottery_info);
            }

            $sharedata = array(
                'themeid' => $themeid,
                'fopenid' => $_G['openid'],
                'fromuid' => $_G['member']['uid'],
                'workerid' => $_G['member']['uid'],
                'flag' => 1,
            );
            if ($system['gongzhong'] == '1') {
                $domaintxt = $system['domainhead1'];
            } else {
                $domaintxt = DOMAIN0;
            }
            $workerurl = $_G['url_scheme'] . $domaintxt . "/" . createMobileUrl('index', $sharedata);
            $workerurl = Poster::GetWorkerUrl($system, $workerurl, MODULE_NAME . "员工:" . $baseinfo['myworker']['username']);
            //贝莱
            $user_course_total = [];
            if ($system['softstyle'] == 108) {
                if ($level == 1) {
                    $sjid = 0;//超级管理员
                }
                if ($level == 2 || $level == 3) {
                    $sjid = '';
                    $worker_item = db_get(t_worker, ['themeid' => $themeid, 'uid' => $_G['member']['uid']]);
                    if ($worker_item) {
                        $sjid = $worker_item['company'];
                    }
                }
                require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
                require_once get_path('plugin/beilai/core/model.php');
                //判断是否隐藏
                $item = \BeilaiModel::getRewardByWhere(['themeid' => $themeid]);
                $other_config = json_decode($item['other_config'], true);
                $show_course_flag = $other_config['show_course_flag'];//显示课程选择数 以及统计数据
                $user_course_total = [];
                if ($level == 1) {
                    $user_course_total = \BeilaiModel::getUserFlagBySjId($themeid, $sjid, 0, 1);
                }
                $user_coupon_total = \BeilaiModel::getUserCouponBySjId($themeid, $sjid, 0, 0);
            }
            //教培
            if ($system['softstyle'] == 109) {
                $level = (int)$level;
                if ($level == 1) {
                    $sjid = 0;//超级管理员
                }
                if ($level == 2 || $level == 3) {
                    $sjid = '';
                    $worker_item = db_get(t_worker, ['themeid' => $themeid, 'uid' => $_G['member']['uid']]);
                    if ($worker_item) {
                        $sjid = $worker_item['company'];
                    }
                }
                require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
                require_once get_path('plugin/education/core/model.php');
                $user_course_total = \EducationModel::getUserFlagBySjId($themeid, $sjid, 0, 1);
                $user_coupon_total = \EducationModel::getUserCouponBySjId($themeid, $sjid, 0, 0);
            }

            //商家多选产品核销
            if ($system['mulit_products'] == 1) {
                if ($level == 1) {
                    $sjid = 0;//超级管理员
                }
                if ($level == 2 || $level == 3) {
                    $sjid = '';
                    $worker_item = db_get(t_worker, ['themeid' => $themeid, 'uid' => $_G['member']['uid']]);
                    if ($worker_item) {
                        $sjid = $worker_item['company'];
                    }
                }

                require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
                require_once get_path('plugin/sjmulitverify/core/model.php');
                if (!$sjid && $level == 1) {
                    $sj_list = SjMulitVerifyModel::getShangjiaList();
                    $sj_mulit_verify = [];
                    $all_total = 0;
                    if ($sj_list) {
                        foreach ($sj_list as $k => $v) {
                            $tmp_total = (int)SjMulitVerifyModel::getSjProductTotal($themeid, $v['id']);
                            $order_total = (int)SjMulitVerifyModel::getOrderTotalByWhere($themeid);
                            $total = ($tmp_total * $order_total);
                            $all_total += $total;
                            $tmp_arr = ['title' => $v['name'], 'total' => $total, 'sj_id' => $v['id']];
                            array_push($sj_mulit_verify, $tmp_arr);

//                            $sj_item_product_total = SjMulitVerifyModel::getUserProductTotalBySjId($themeid,0,0,$v['id']);
//                            $all_total += $sj_item_product_total;
//                            array_push($sj_mulit_verify,['title'=>$v['name'],'total'=>$sj_item_product_total,'sj_id'=>$v['id']]);
                        }
                    }
                    array_unshift($sj_mulit_verify, ['title' => '全部', 'total' => $all_total, 'sj_id' => 0]);
                } elseif ($sjid && ($level == 2 || $level == 3)) {
                    $sj_products = SjMulitVerifyModel::getSjProductList($themeid, '', 1, $sjid, 0, 0);
                    $sj_mulit_verify = [];
                    $all_total = 0;
                    foreach ($sj_products as $k => $v) {
                        $sj_item_product_total = (int)SjMulitVerifyModel::getOrderTotalByWhere($themeid);
                        $all_total += $sj_item_product_total;
                        array_push($sj_mulit_verify, ['title' => $v['name'], 'total' => $sj_item_product_total, 'p_id' => $v['id']]);
                    }
                    array_unshift($sj_mulit_verify, ['title' => '全部', 'total' => $all_total, 'p_id' => 0]);
                }
            }
            //团人数统计
            $tuan_num_info = Fans::getTuanNumInfo($themeid, $baseinfo['myworker'], $baseinfo['config'], $baseinfo['system']);
            //多选分类
            $dx_products = [];
            if (($baseinfo['config']['shopstype'] == 8 && $baseinfo['config']['shops']) || ($baseinfo['config']['presale']['shopstype'] == 8 && $baseinfo['config']['presale']['shops'])) {
                $dx_cate = $baseinfo['config']['dx_cate'];
                foreach ($dx_cate as $k => $v) {
                    foreach ($v['list'] as $kk => $vv) {
                        $item = [
                            'pid' => $vv['id'],
                            'title' => $vv['name'],
                            'cate_name' => $v['name'],
                            'total' => 0
                        ];
                        array_push($dx_products, $item);
                    }
                }
                $sql = " select count(*) as cnt from " . tablename(t_record) . " where themeid=$themeid  and (status=1 or status=3) and find_in_set(";
                foreach ($dx_products as $key => $val) {
                    $where = $val['pid'] . ",`option`) ";
                    $tmp_sql = $sql . " " . $where . " ";
                    $dx_products[$key]['total'] = db_find($tmp_sql)['cnt'];
                }
            }
            $return_clicent = get_defined_vars();
            return view('fcworker/fc_index', $return_clicent);
        }
    }

    public function X_beCoupon()
    {
        global $_P, $_G;
        $baseinfo = $this->Isworker();
        $theme = $baseinfo['theme'];
        $system = $baseinfo['system'];

        require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
        if ($system['softstyle'] == 108) {
            require_once get_path('plugin/beilai/core/model.php');
            $class = "\BeilaiModel";
        }
        if ($system['softstyle'] == 109) {
            require_once get_path('plugin/education/core/model.php');
            $class = "\EducationModel";
        }
        $page = $_P['page'] ? $_P['page'] : 1;
        $hasNext = true;
        $page_index = max(1, intval($page));
        $page_size = 15;
        $page_start = ($page_index - 1) * $page_size;
        $themeid = $baseinfo['theme']['id'];
        $status = $_P['status'] ? $_P['status'] : 0;
        $c_id = $_P['c_id'] ? $_P['c_id'] : 0;
        $shangjiaid = $_P['shangjiaid'] ? $_P['shangjiaid'] : 0;
        $status_arr = $class::getStatusCouponCount($themeid);

        $level = $baseinfo['myworker']['level'];

        if ($level == 1) {
            if (!$shangjiaid) {
                $shangjiaid = 0;//超级管理员
            }
        }
        if ($level == 2 || $level == 3) {
            $shangjiaid = '';
            $worker_item = db_get(t_worker, ['themeid' => $themeid, 'uid' => $_G['member']['uid']]);
            if ($worker_item) {
                $shangjiaid = $worker_item['company'];
            }
        }
        $page_total = $class::getUserCouponFlag($themeid, $shangjiaid, '', 0, 0, '', '', 0, true, $c_id, $status);
        $list = $class::getUserCouponFlag($themeid, $shangjiaid, '', $page_start, $page_size, '', '', 0, false, $c_id, $status);
        $max_page = ceil($page_total / $page_size);
        if ($max_page <= $page) {
            $hasNext = false;
        }

        if ($_G['ispost']) {
            $temp_html_taun = '';
            $sort = (($page - 1) * $page_size);
            foreach ($list as $key => $val) {
                $new_sort = $sort + ($key + 1);
                $temp_html_taun .= '<tr class="new_tr">' . PHP_EOL .
                    '<td>' . $new_sort . '</td>' . PHP_EOL .
                    '<td>' . PHP_EOL . '<img src="' . $val['avatar'] . '" class="td-img">' . PHP_EOL;
                $temp_html_taun .= '</td>' . PHP_EOL .
                    '<td>' . $val['username'] . '<br>' . $val['mobile'] . '</td>' . PHP_EOL .
                    '<td>' . $val['name'] . '</td>' . PHP_EOL;
                if ($val['status'] == 2) {
                    $temp_html_taun .= '<td ><span class="label label-success">已使用</span></td>';
                } else {
                    $temp_html_taun .= '<td ><span class="label label-danger" >未使用</span></td>';
                }
                $updated_at = '';
                if ($val['status'] == 2) {
                    $updated_at = $val['updated_at'];
                }
                $temp_html_taun .= '<td>' . $updated_at . '</td>' . PHP_EOL .
                    '</tr>';
            }

            return_json(0, '', ['hasNext' => $hasNext, 'list' => $temp_html_taun]);
        } else {
            $return_clicent = get_defined_vars();
            return view('fcworker/fc_be_coupon', $return_clicent);
        }
    }

    public function X_myinfo()
    {
        global $_P, $_G;
        $wx = $_G['platform']['jssdkconfig'];
        $main = 'x_myinfo';
        $baseinfo = $this->Isworker();
        $theme = $baseinfo['theme'];
        $system = $baseinfo['system'];
        $result = Fans::w_myinfo($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        if ($result['error'] == 1) {
            return return_msg($result['msg']);
        } else {
            $themeid = $baseinfo['theme']['id'];
            $fans = $my = $result['my'];
            $myreport = $result['myreport'];
            $myteam = $result['myteam'];
            $mycompany = $result['mycompany'];
            $day = date('d');
            if (strlen($day) < 1) {
                $day = '0' . $day;
            }
            if (count($myreport) > 1 || count($mycompany) > 1 || count($myteam) > 1) {
//                if ($day == substr($myreport[1]['riqi'],3,2)){
//                    array_splice($myreport,0,1);
//                }
                if ($day == substr($mycompany[1]['riqi'], 3, 2)) {
                    array_splice($mycompany, 0, 1);
                }
                if ($day == substr($myteam[1]['riqi'], 3, 2)) {
                    array_splice($myteam, 0, 1);
                }
            }
            $workertips = $result['workertips'];
            $teamname = $fans['teamname'];
            $username = $fans['username'];
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            $return_clicent = get_defined_vars();
            return view('fcworker/fc_myinfo', $return_clicent);
        }
    }

    public function X_rank()
    {
        global $_P, $_G;
        $wx = $_G['platform']['jssdkconfig'];
        $main = $do = 'x_rank';
        $op = $_P['op'];
        $baseinfo = $this->Isworker();
        $theme = $baseinfo['theme'];
        $system = $baseinfo['system'];
        $show = $_P['show'] ? $_P['show'] : '';
        $tag = $_P['tag'] ? $_P['tag'] : '';
        $starttime = $_P['starttime'] ? $_P['starttime'] : date("Y-m-d 00:00:00");
        $endtime = $_P['endtime'] ? $_P['endtime'] : date("Y-m-d 23:59:59");
        $result = Fans::w_rank($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        if ($result['error'] == 1) {
            return return_msg($result['msg']);
            die();
        } else {
            $themeid = $baseinfo['theme']['id'];
            $paixu = $_P['paixu'] ? $_P['paixu'] : 'record';
            $companylist = $result['companylist'];
            $companytoday = $result['companytoday'];
            if ($baseinfo['config']['isrank'] || $baseinfo['myworker']['level'] == 1) {
                $teamlist = $result['teamlist'];
                $teamtoday = $result['teamtoday'];
            } else {
                $teamlist = [];
                $teamtoday = [];
            }
            if (!$tag) {
                if ($companylist) {
                    $tag = 'all_shop';
                } else {
                    $tag = 'all_group';
                }
            }
            $workerlist = $result['workerlist'];
            $workertoday = $result['workertoday'];
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            $return_clicent = get_defined_vars();
            return view('fcworker/fc_rank', $return_clicent);
        }
    }

    public function X_group()
    {
        global $_P, $_G;
        $wx = $_G['platform']['jssdkconfig'];
        $main = 'x_group';
        $op = $_P['op'];
        $tuannum = $_P['tuannum'] ? $_P['tuannum'] : 0;
        $baseinfo = $this->Isworker();
        $theme = $baseinfo['theme'];
        $system = $baseinfo['system'];
        $result = Fans::W_group($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        if ($result['error'] == 1) {
            return_json(1, $result['msg']);
        } else {
            $themeid = $baseinfo['theme']['id'];
            $page = $result['page'];
            $hasNext = $result['hasNext'];
            $groupsnumall = $result['info']['groupsnumall'];
            $groupsnum = $result['info']['groupsnum'];
            $groupsnumtuanyuan = $result['info']['groupsnumtuanyuan'];
            $groups = $result['list'];
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            if ($_G['ispost']) {
                $append_html = '';
                foreach ($groups as $k => $item) {
                    $append_html .= '<div class="teamBar">' . PHP_EOL . '<div class="teamTit">' . PHP_EOL;
                    $append_html .= '<p>团号-' . ($item['id'] + 10000) . '</p>' . PHP_EOL;
                    $append_html .= '</div>' . PHP_EOL . '<div class="peopleInfor">' . PHP_EOL . '<div class="peopleImg">' . PHP_EOL;
                    $append_html .= '<img src="' . $item['avatar'] . '">' . PHP_EOL;
                    $append_html .= '</div>' . PHP_EOL . '<div class="peopleTxt">' . PHP_EOL . '<h2>';
                    $append_html .= $item['username'] . '</h2>' . PHP_EOL;
                    $append_html .= '<p>昵称：' . $item['nickname'] . '</p>' . PHP_EOL . $item['shenfen'] . '</div>';
                    $append_html .= '<div class="teamNum">团人数:' . $item['tuannum'] . '人</div>' . PHP_EOL;
                    $append_html .= '<a href="tel:' . $item['mobile'] . '" class="telBtn"></a>' . PHP_EOL . '</div>' . PHP_EOL;
                    $append_html .= '<dl>' . $item['tuanyuan'] . '</dl>' . PHP_EOL . '</div>' . PHP_EOL;
                }
                $result['append_html'] = $append_html;
                return_json(0, '', $result);
            }
            $return_clicent = get_defined_vars();
            return view('fcworker/fc_group', $return_clicent);
        }
    }

    public function X_order()
    {
        global $_P, $_G;
        $wx = $_G['platform']['jssdkconfig'];
        $main = 'x_order';
        $op = isset($_P['op']) ? $_P['op'] : '';
        $baseinfo = $this->Isworker();
        //删除重复员工
        $themeid = intval($_P['themeid']);
        $theme = $baseinfo['theme'];
        $system = $baseinfo['system'];
        $searchtxt = $_P['searchtxt'];

        Fans::WorkerDeleteChongfu($themeid);
        $result = Fans::W_order($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);

        if ($result['error'] == 1) {
            return_json(1, $result['msg']);
        } else {
            $scan = isset($_P['scan']) ? $_P['scan'] : 0;
            $page = $result['page'];
            $hasNext = $result['hasNext'];
            $config = $baseinfo['config'];
            $list = $result['list'];
            $info = $result['info'];

            $is_shop_plan = $system['is_shop_plan'];
            if ($is_shop_plan) {

                require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
                require_once get_path('plugin/shopplan/core/model.php');

                foreach ($list as $key => $val) {
                    if (!$is_shop_plan) {
                        $plan_shop_info = [];
                    } else {
                        $plan_shop_info = \ShopplanModel::getUserPlanByUid($val['uid'], $themeid);
                    }
                    if ($plan_shop_info) {
                        $temp_str = '预约时间：' . substr($plan_shop_info['plan_at'], 0, -3);
                        array_push($list[$key]['moreinfo'], $temp_str);
                    } else {
                        if ($is_shop_plan) {
                            $temp_str = '预约时间：用户未预约';
                            array_push($list[$key]['moreinfo'], $temp_str);
                        }
                    }
                }
            }
            if ($system['softstyle'] == 109) {
                if ($system['softstyle'] == 109) {

                    require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
                    require_once get_path('plugin/education/core/model.php');
                } else {

                    require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
                    require_once get_path('plugin/beilai/core/model.php');
                }
                foreach ($list as $index => $row) {
                    $tmp_course_list = $tmp_gift_list = [];
                    if ($system['softstyle'] == 109) {
                        $tmp_course_list = \EducationModel::getUserCourseFlag($themeid, 0, '', 0, 10, '', '', $row['id']);
                        $tmp_gift_list = \EducationModel::getUserGift($themeid, 0, '', 0, 10, '', '', 0, 0, 0, $row['id']);
//                        $list[$index]['coupon_list'] = EducationModel::getUserCouponFlag($themeid,0,'',0,1,'','',$row['id']);
                    }
                    //贝莱判断
                    if ($system['softstyle'] == 108) {
                        $tmp_course_list = \BeilaiModel::getUserCourseFlag($themeid, 0, '', 0, 10, '', '', $row['id']);
                        $tmp_gift_list = \BeilaiModel::getUserGift($themeid, 0, '', 0, 10, '', '', 0, 0, 0, $row['id']);
//                        $list[$index]['coupon_list'] = BeilaiModel::getUserCouponFlag($themeid,0,'',0,1,'','',$row['id']);
                    }
                    if ($tmp_course_list) {
                        $tmp_course_str = '';
                        foreach ($tmp_course_list as $k => $v) {
                            $tmp_course_str .= $v['name'] . ';';
                        }
                        $temp_str = '选择课程：' . $tmp_course_str;
                        array_push($list[$index]['moreinfo'], $temp_str);
                    }
                    if ($tmp_gift_list) {
                        $tmp_gift_str = '';
                        foreach ($tmp_gift_list as $k => $v) {
                            $tmp_gift_str .= $v['name'] . ';';
                        }
                        $temp_str = '获得礼品：' . $tmp_gift_str;
                        array_push($list[$index]['moreinfo'], $temp_str);
                    }
                }
            }

            $result['jubf'] = $baseinfo['jubf'];
            $jishu = $result['jishu'] = $baseinfo['jishu'];
            if ($_G['ispost'] && $_P['op2'] != 'search') {
                $append_html = '';
                foreach ($list as $key => $item) {

//                    peoPle
                    $append_html .= '<div class="peoPle">' . PHP_EOL;
//                      peopleTime
                    $append_html .= '<div class="peopleTime"><div>' . $item['sid'] . '.' . $item['addtime'] . '</div><div class="hexiao_tips"';
                    if ($item['hexiaotips'] == '未核销') {
                        $append_html .= 'style="color:#939393"';
                    }
                    $append_html .= '>' . $item['hexiaotips'] . '</div></div>' . PHP_EOL;
//                      peopleInfor
                    $append_html .= '<div class="peopleInfor">' . PHP_EOL . '<div class="peopleImg">' . PHP_EOL . '<img src="' . $item['avatar'] . '">' . PHP_EOL . '</div>' . PHP_EOL . '<div class="peopleTxt">' .
                        '<h2>' . $item['username'] . '</h2>' . PHP_EOL .
                        '<p>昵称：' . $item['nickname'] . '</p>' . PHP_EOL .
                        '<p>' . $item['workernameall'] . '</p>' . PHP_EOL;
                    $append_html .= '</div>' . PHP_EOL;
                    $append_html .= '<div class="teamNum" style="position: relative">' . PHP_EOL;
                    if ($item['tuannum'] > 1 && $info['maxcount'] > 0) {
                        $append_html .= '<div class="teamNum" style="position: absolute;top: -25px"><a href="javascript:void(0);" data-method="gotogroup" data-id="' . $item['pid'] . '" class="lookteam">查看团成员</a><div class="teamNumbg"></div></div>' . PHP_EOL;
                    }
                    if ($item['type'] == 8) {
                        $append_html .= '<div class="teamNum"><a href="javascript:void(0);" data-id="' . $item['pid'] . '" class="teamNum">补余款</a></div>' . PHP_EOL;
                    }
                    if ($info['maxcount'] > 0) {
                        $append_html .= '<div class="teamNum"><a href="javascript:void(0);" data-method="gotogroup" data-id="' . $item['pid'] . '" class="teamNum">' . $item['tuannum'] . '人团:' . $item['shenfen'] . '</a></div>' . PHP_EOL;
                    }
                    $append_html .= '</div>' . PHP_EOL;
                    $append_html .= '<a href="tel:' . $item['mobile'] . '" class="telBtn"></a>' . PHP_EOL . '</div>' . PHP_EOL;
                    //information
                    $append_html .= '<div class="information">' . PHP_EOL;
                    foreach ($item['moreinfo'] as $k => $v) {
                        $append_html .= '<p>' . $v . '</p>' . PHP_EOL;
                    }


                    $append_html .= '</div>' . PHP_EOL;
                    //payMoneytxt
                    $append_html .= '<div class="payMoneytxt">' . PHP_EOL;
                    $append_html .= $item['remain_amount'] . $item['statustxt'];
                    if ($item['status'] == 1) {
                        $append_html .= '<span>￥<i>' . $item['fee'] . '</i></span>' . PHP_EOL;
                    }
                    $append_html .= '</div>' . PHP_EOL;
                    //controlBox


                    if ($item['member_info']['isshow']) {
                        $append_html .= '<div class="note_txt">' . PHP_EOL;
                        $append_html .= $item['member_info']['is_member'] . "<span>" . $item['member_info']['chongzhi'] . "</span>" . $item['member_info']['member_beizhu'];
                        $append_html .= '</div>' . PHP_EOL;
                    }

                    $append_html .= '<div class="controlBox">' . PHP_EOL . '<span class="contBtn">更多信息</span>' . PHP_EOL;


                    if ($info['isedit']) {
                        $append_html .= '<a href="javascript:void(0);" data-id="' . $item['id'] . '" data-method="gotoedit" class="checkBtn changeBtn">修改订单</a>' . PHP_EOL;
                    }
                    if ($item['status'] == 3 && !$item['openid']) {
                        $append_html .= '<a href="javascript:void(0);" data-id="' . $item['id'] . '" data-method="gotoinputbd" data-op="getinfo"  class="checkBtn">绑定微信</a>' . PHP_EOL;
                    }
                    if ($item['status'] == 3 && $item['openid']) {
                        $append_html .= '<a href="javascript:void(0);" data-id="' . $item['id'] . '" data-method="gotoinputbd" data-op="reset"  class="checkBtn">重绑微信</a>' . PHP_EOL;
                    }

                    if ($item['status'] != 3 && $item['status'] > 0) {
                        $append_html .= '<a href="javascript:void(0);" data-method="example" data-id="' . $item['id'] . '" class="checkBtn">交易凭证</a>' . PHP_EOL;
                    }
                    if ($info['is_tuan_order'] == 1 && $item['status'] != 3 && $item['status'] > 0) {
                        $append_html .= '<a href="javascript:void(0);" data-id="' . $item['id'] . '" data-method="showQr" class="checkBtn checkBtn1 ckSmall">海报</a>' . PHP_EOL;
                    }
                    $append_html .= '</div>' . PHP_EOL . '</div>' . PHP_EOL;
                }
                $result['append_html'] = $append_html;
                return_json(0, '', $result);
            } else {
                $return_clicent = get_defined_vars();
                $return_clicent = get_defined_vars();
                return view('fcworker/fc_order', $return_clicent);
            }

        }
    }

    public function X_lottery()
    {

        require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
        require_once get_path('plugin/lottery/core/model.php');
        global $_P, $_G;
        $wx = $_G['platform']['jssdkconfig'];
        $main = 'X_lottery';
        $op = isset($_P['op']) ? $_P['op'] : '';
        $uid = isset($_P['uid']) ? $_P['uid'] : '';
        $p_id = $_P['p_id'];
        $page = $_P['page'] ? $_P['page'] : 1;
        $hasNext = true;
        $page_index = max(1, intval($page));
        $page_size = 50;
        $page_start = ($page_index - 1) * $page_size;


        $baseinfo = $this->Isworker();
        $themeid = intval($_P['themeid']);
        $theme = $baseinfo['theme'];
        $system = $baseinfo['system'];
        $searchtxt = $_P['searchtxt'];

        $prize_arr = \LotteryModel::getPrizeFlagCount($themeid, true);
        $lists = \LotteryModel::getDefaultLtList($themeid, 0, $p_id, 0, 0, $uid);
        $list = \LotteryModel::getDefaultLtList($themeid, 0, $p_id, $page_start, $page_size, $uid);
        $worklist = Worker::getworkerlist($system, $themeid);
        foreach ($list as $key => $row) {
            if ($row['from_type'] == 'red_envelope') {
                $item = LotteryModel::getRpFlagItem(['themeid' => $themeid, 'f_id' => $row['f_id']]);
                if ($item && $row['red_envelopes_amount_min'] != $row['red_envelopes_amount_max']) {
                    $list[$key]['title'] = '现金红包' . $item['amount'] . '元';
                }
            }
            if (!empty($row['workerid'])) {
                $r = Worker::getWokerName($system, $themeid, $row['workerid'], $worklist);
                $list[$key]['workername'] = $r['workername'];
                $list[$key]['teamname'] = $r['teamname'];
                $list[$key]['companyname'] = $r['companyname'];
            }
        }
        $max_page = ceil(count($lists) / $page_size);
        if ($max_page <= $page) {
            $hasNext = false;
        }
        if ($_G['ispost']) {
            $temp_html_taun = '';
            $sort = (($page - 1) * $page_size);
            foreach ($list as $key => $val) {
                $new_sort = $sort + ($key + 1);
                $temp_html_taun .= '<tr class="new_tr">' . PHP_EOL .
                    '<td>' . $new_sort . '</td>' . PHP_EOL .
                    '<td>' . PHP_EOL . '<img src="' . $val['avatar'] . '" class="td-img">' . PHP_EOL;
                $temp_html_taun .= '</td>' . PHP_EOL .
                    '<td>' . $val['username'] . '</td>' . PHP_EOL .
                    '<td>' . $val['title'] . '</td>' . PHP_EOL .
                    '<td>' . $val['created_at'] . '</td>' . PHP_EOL .
                    '<td style="text-align: center;padding-left: .34rem;"><a href="tel:' . $val['mobile'] . '" class="telBtn" style="float: none;"></a></td>' . '</tr>';
            }

            return_json(0, '', ['hasNext' => $hasNext, 'page_total' => $max_page, 'list' => $temp_html_taun]);
        } else {
            $return_clicent = get_defined_vars();
            return view('fcworker/fc_lottery', $return_clicent);
        }
    }

    /**
     * Desc:商家多选产品核销信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/23 14:23
     */
    public function X_mulitProduct()
    {

        require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
        require_once get_path('plugin/sjmulitverify/core/model.php');
        $baseinfo = $this->Isworker();
        global $_P, $_G;
        $wx = $_G['platform']['jssdkconfig'];
        $main = 'X_mulitProduct';
        $themeid = intval($_P['themeid']);
        extract(SjMulitVerifyModel::formatAdminMulitInfo($baseinfo));
        if ($_G['ispost']) {
            $temp_html_taun = '';
            $sort = (($page - 1) * $page_size);
            foreach ($list as $key => $val) {
                $new_sort = $sort + ($key + 1);
                $temp_html_taun .= '<tr class="new_tr">' . PHP_EOL .
                    '<td>' . $new_sort . '</td>' . PHP_EOL .
                    '<td>' . PHP_EOL . '<img src="' . $val['avatar'] . '" class="td-img"><br>' . $val['username'] . PHP_EOL;
                $temp_html_taun .= '</td>' . PHP_EOL .
                    '<td>' . mb_substr($val['name'], 0, 5) . '</td>' . PHP_EOL;
                if ($val['status'] == 1) {
                    //未核销
                    $temp_html_taun .= '<td><span style="color: #ffffff;border: 1px solid #ff0000;padding: 4px;background-color: #ff0000;">未核销</span></td>';
                    $temp_html_taun .= '<td></td>' . PHP_EOL;
                } else {
                    //已核销
                    $temp_html_taun .= '<td><span style="color: #ffffff;border: 1px solid #07c160;padding: 4px;background-color: #07c160;">已核销</span></td>';
                    $temp_html_taun .= '<td>' . $val['workername'] . '<br>' . $val['updated_at'] . '</td>' . PHP_EOL;
                }
                $temp_html_taun .=
                    '<td style="text-align: center;padding-left: .34rem;"><a href="tel:' . $val['mobile'] . '" class="telBtn" style="float: none;"></a></td>' . '</tr>';
            }
            return_json(0, '', ['hasNext' => $hasNext, 'page_total' => $max_page, 'list' => $temp_html_taun]);
        } else {
            $return_clicent = get_defined_vars();
            return view('fcworker/fc_products', $return_clicent);
        }
    }

    /**
     * Desc:夺宝领取记录列表
     * User: mf
     * Time: 2023/11/8 10:06
     */
    public function X_giftRecord()
    {
        global $_P, $_G;
        $themeid = intval($_P['themeid']);
        $taskid = intval($_P['taskid']);
        $classify = $_P['classify'];
        $baseinfo = $this->Isworker();

        require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
        require_once get_path('plugin/gift/core/model.php');
        $list = \GiftModel::giftRecord($baseinfo, $themeid);

        if ($_G['ispost']) {
            $html = '';
            foreach ($list as $key => $val) {
                $new_sort = $val['id'] + 985;
                $html .= '<tr class="new_tr">' . PHP_EOL .
                    '<td>' . $new_sort . '</td>' . PHP_EOL .
                    '<td>' . PHP_EOL . '<img src="' . $val['avatar'] . '" class="td-img"><br>' . $val['username'] . PHP_EOL;
                $html .= '</td>' . PHP_EOL .
                    '<td>' . mb_substr($val['name'], 0, 5) . '</td>' . PHP_EOL;
                if ($val['status'] == 1) {
                    //未核销
                    $html .= '<td><span style="color: #ffffff;border: 1px solid #ff0000;padding: 4px;background-color: #ff0000;">未核销</span></td>';
                    $html .= '<td></td>' . PHP_EOL;
                } else if ($val['status'] == -2) {
                    //已失效
                    $html .= '<td><span style="color: #ffffff;border: 1px solid #ccc;padding: 4px;background-color: #ccc;">已失效</span></td>';
                    $html .= '<td>' . $val['workername'] . '<br>' . $val['updated_at'] . '</td>' . PHP_EOL;
                } else if ($val['status'] == 2) {
                    //已核销
                    $html .= '<td><span style="color: #ffffff;border: 1px solid #07c160;padding: 4px;background-color: #07c160;">已核销</span></td>';
                    $html .= '<td>' . $val['workername'] . '<br>' . $val['updated_at'] . '</td>' . PHP_EOL;
                }
                $html .=
                    '<td style="text-align: center;padding-left: .34rem;"><a href="tel:' . $val['mobile'] . '" class="telBtn" style="float: none;"></a></td>' . '</tr>';

            }
            return_json(0, 'ok', ['list' => $html, 'page' => $_P['page']]);
        }

        $invite_gift_list = \GiftModel::conditionStatistics($baseinfo['system'], $themeid, $baseinfo['myworker']);
        $return_clicent = get_defined_vars();
        return view('fcworker/fc_giftrecord', $return_clicent);
    }

    public function X_ltExample()
    {
        global $_P, $_G;
        $baseinfo = $this->Isworker();
        $themeid = intval($_P['themeid']);
        $theme = $baseinfo['theme'];
        $cache_key = 'worker_lt_example_uid';
        cache_write($cache_key, $baseinfo['myworker']['uid']);
        $jump_url = createMobileUrl('index', array('themeid' => $themeid, 'fx' => 9), true);
        return $this->redirect($jump_url);
//        require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
//        require_once get_path('plugin/lottery/core/model.php');
//        if ($_G['ispost']) {
//            //post请求
//            $res = \LotteryModel::dummyConvert($baseinfo['config'], $baseinfo['theme'], $baseinfo['system'], 'mobile');
//            return_json(0, '操作成功', $res);
//        }
//        $return_clicent = get_defined_vars();
//        return view('fcworker/fc_lt_example', $return_clicent);
    }

    public function X_beilai()
    {
        global $_P, $_G, $_S;

        require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';


        $p_id = $_P['p_id'];
        $sjid = isset($_P['sjid']) ? $_P['sjid'] : 0;
        $page = $_P['page'] ? $_P['page'] : 1;
        $hasNext = true;
        $themeid = intval($_P['themeid']);
        $page_index = max(1, intval($page));
        $page_size = 20;
        $page_start = ($page_index - 1) * $page_size;

        $baseinfo = $this->Isworker();
        if ($baseinfo['system']['softstyle'] == 109) {
            require_once get_path('plugin/education/core/model.php');
            $class = new \EducationModel();
        } else {
            require_once get_path('plugin/beilai/core/model.php');
            $class = new \BeilaiModel();
        }
        if (!$baseinfo) {
            if (!$_G['ispost']) {
                return return_msg('非员工无法访问');
                die();
            } else {
                return_json(1, '非员工无法访问', '');
            }
        }
        $result = Fans::w_index($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        $level = (int)$result['level'];
        if ($result['error'] == 1) {
            if (!$_G['ispost']) {
                return return_msg($result['msg']);
                die();
            } else {
                return_json(1, $result['msg'], '');
            }
        } else {
            if ($level > 3) {
                return_json(1, '非员工无法访问', '');
                die();
            }
            $worker_item = db_get(t_worker, ['themeid' => $themeid, 'uid' => $_G['member']['uid']]);
            if ($worker_item) {
                $sjid = $worker_item['company'];
            }
            $sj_list = [];
            if ($level == 1) {
                $sjid = 0;
//                if ($baseinfo['myworker']['company']){
//                    $sjid = $baseinfo['myworker']['company'];
//                }
                $sj_list = [['sjid' => 0, 'name' => '全部']];
                $shangjia_list = $class::getShangjiaList();
                if ($shangjia_list) {
                    foreach ($shangjia_list as $key => $val) {
                        $sj_course_total = $class::getCourseTotal($themeid, $val['id']);
                        if ($sj_course_total > 0) {
                            array_push($sj_list, ['sjid' => $val['id'], 'name' => $val['name']]);
                        }
                    }
                }
                if ($_P['sjid']) {
                    $sjid = $_P['sjid'];
                }
            } else {
                //判断商家id是否为当前用户的绑定的商家id
                //判断课程id是否为当前用户绑定的商家id
                $course_item = $class::getCourseItemById($themeid, $p_id);
                if (!$course_item || ($course_item && $course_item['shangjiaid'] != $sjid)) {
                    $p_id = 0;
                }
            }
            $type_arr = $class::getUserFlagBySjId($themeid, $sjid, 0, 1);

            $themeid = intval($_P['themeid']);
            $theme = $baseinfo['theme'];
            $system = $baseinfo['system'];

            $search_data = isset($_P['searchtxt']) ? $_P['searchtxt'] : '';
            if ($search_data) {
                $search_data = '%' . $search_data . '%';
            }
            $sj_courses_lists = $class::getUserCourseFlag($themeid, $sjid, $search_data, 0, 0, '', '', 0, 0, $p_id);
            $sj_courses_list = $class::getUserCourseFlag($themeid, $sjid, $search_data, $page_start, $page_size, '', '', 0, 0, $p_id);
            $max_page = (int)ceil(count($sj_courses_lists) / $page_size);

            if ($max_page <= $page) {
                $hasNext = false;
            }
            foreach ($sj_courses_list as $k => $v) {
                if ($v['status'] && $v['workerid']) {
                    $check_worker = db_get(t_worker, ['themeid' => $themeid, 'uid' => $v['workerid']]);
                    $sj_courses_list[$k]['verify_name'] = $check_worker['username'] ? $check_worker['username'] : '';
                    $sj_courses_list[$k]['updated_at'] = $check_worker['username'] ? $v['updated_at'] : '';
                } else {
                    $sj_courses_list[$k]['updated_at'] = '';
                }
            }
            if ($_G['ispost']) {
                $temp_html_taun = '';
                $sort = (($page - 1) * $page_size);
                foreach ($sj_courses_list as $key => $val) {
                    $new_sort = $sort + ($key + 1);
                    $tmp_id = $val['id'];
                    $tmp_address = $val['address'];
                    $check_str = "<td onclick='verifyItem($tmp_id,`$tmp_address`)'><span class='label label-danger' >未核销</span>";
                    if ($val['status'] == 1) {
                        $check_str = '<td ><span class="label label-success">已核销</span>';
                    }
                    $first_html = '<tr class="new_tr" data-id="' . $val['id'] . '" data-shangjiaid="' . $val['shangjiaid'] . '" data-uid="' . $val['uid'] . '>';
                    if ($baseinfo['system']['softstyle'] == 109) {
                        $first_html = '<tr class="new_tr" onclick="openAlert(this)" data-id="' . $val['id'] . '" data-shangjiaid="' . $val['shangjiaid'] . '" data-uid="' . $val['uid'] . '>';
                    }
                    $temp_html_taun .= $first_html . PHP_EOL .
                        '<td>' . $new_sort . '</td>' . PHP_EOL .
                        '<td>' . PHP_EOL . '<img src="' . $val['avatar'] . '" class="td-img">' . PHP_EOL . '</td>' . PHP_EOL .
                        '<td>' . $val['username'] . '<br>' . $val['mobile'] . '</td>' . PHP_EOL .
                        '<td>' . $val['name'] . '</td>' . PHP_EOL .
                        $check_str . '<br/>' . $val['verify_name'] . '</td>' . PHP_EOL .
                        '<td>' . $val['updated_at'] . '</td>' . '</tr>';
                }

                return_json(0, '', ['hasNext' => $hasNext, 'page_total' => $max_page, 'list' => $temp_html_taun]);
            } else {
                $return_clicent = get_defined_vars();
                $return_clicent = get_defined_vars();
                return view('fcworker/fc_beilai', $return_clicent);
            }
        }
    }

    public function X_editCourse()
    {
        global $_G, $_P, $_S, $_C;
        $baseinfo = $this->Isworker();
        require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
        if ($baseinfo['system']['softstyle'] == 109) {
            require_once get_path('plugin/education/core/model.php');
            $class = new \EducationModel();
        } else {
            require_once get_path('plugin/beilai/core/model.php');
            $class = new \BeilaiModel();
        }
        $themeid = intval($_P['themeid']);
        if ($themeid <= 0) {
            $themeid = Theme::getDefaultThemenew();
        }
        $shangjiaid = $_P['shangjia_id'] ? $_P['shangjia_id'] : 0;
        $course_id = $_P['course_id'];
        $uid = $_P['uid'];


        //获取当前用户已选课程的ids
        $has_list = \EducationModel::getUserCanEditCourseList($themeid, $shangjiaid, $uid);
        return_json(0, '操作成功', $has_list);
    }

    public function X_sureEditCourse()
    {
        global $_G, $_P, $_S, $_C;
        $themeid = intval($_P['themeid']);
        if ($themeid <= 0) {
            $themeid = Theme::getDefaultThemenew();
        }
        $course_id = $_P['course_id'];//记录id
        $shangjia = $_P['shangjia'];
        $course = $_P['course'];
        $adress = $_P['adress'];
        if (!$course_id) {
            return show_json(0, ['msg' => '记录参数缺失']);
        }
        if (!$shangjia) {
            return show_json(0, ['msg' => '商家参数缺失']);
        }
        if (!$course) {
            return show_json(0, ['msg' => '修改课程缺失']);
        }
        if (!$adress) {
            return show_json(0, ['msg' => '修改地址缺失']);
        }
        $data = [
            'shangjiaid' => $shangjia,
            'course_id' => $course,
            'address' => $adress,
        ];
        $where = [
            'id' => $course_id,
            'themeid' => $themeid
        ];
        $data['updated_at'] = date("Y-m-d H:i:s", time());
        $res = db_update(t_shangjia_address_user_course, $data, $where);
        if (!$res) {
            return_json(1, '修改失败');
        } else {
            return_json(0, '修改成功');
        }
    }

    public function X_beilaiVerify()
    {
        global $_P, $_G;

        require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';


        $themeid = intval($_P['themeid']);
        $baseinfo = $this->Isworker();
        if ($baseinfo['system']['softstyle'] == 109) {
            require_once get_path('plugin/education/core/model.php');
            $class = new \EducationModel();
        } else {
            require_once get_path('plugin/beilai/core/model.php');
            $class = new \BeilaiModel();
        }
        if (!$baseinfo) {
            return_json(1, '非员工无法访问', '');
        }
        if ($_G['ispost']) {
            $result = Fans::w_index($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
            if ($result['error'] == 1) {
                return_json(1, $result['msg'], '');
            } else {
                $level = $result['level'];
                if ($level > 3) {
                    return_json(1, '非员工无核销权限', '');
                    die();
                }
                $flag_id = isset($_P['id']) ? $_P['id'] : 0;
                if (!$flag_id) {
                    return_json(1, '核销课程记录不存在', '');
                } else {
                    //判断当前课程是是当前用户的商家
                    if ($level == 2 || $level == 3) {
                        $worker_item = db_get(t_worker, ['themeid' => $themeid, 'uid' => $_G['member']['uid']]);
                        if (!$worker_item) {
                            return_json(1, '非员工无法访问', '');
                            die();
                        }
                    }
                    //核销的逻辑  超级管理员  课程的商家管理员以及员工可以核销
                    //判断当前用户的身份是否为超级管理员
                    $flag = $class::getUserCourseAddress(['themeid' => $themeid, 'id' => $flag_id]);
                    if (!$flag || ($flag['status'] == 1 && $flag['workerid'])) {
                        return_json(1, '该课程记录不存在或已核销', '');
                        die();
                    }
                    if ($flag['shangjiaid'] != $worker_item['company'] && $level == 2 || $level == 3) {
                        return_json(1, '该课程无权限核销', '');
                        die();
                    }
                    $where = ['id' => $flag_id, 'themeid' => $themeid, 'status' => 0];
                    $data = ['status' => 1, 'workerid' => $_G['member']['uid'], 'updated_at' => date("Y-m-d H:i:s", time())];
                    $res = $class::editUserCourseAddress($where, $data);
                    if (!$res) {
                        return_json(1, '课程已核销或课程记录不存在，请检查后重试', '');
                    } else {
                        return_json(0, '课程核销成功', '');
                    }
                }

            }
        }
    }

    public function X_orderedit()
    {
        global $_P, $_G;
        $wx = $_G['platform']['jssdkconfig'];
        $main = 'x_order';
        $id = $_P['id'];
        $baseinfo = $this->Isworker();
        $themeid = intval($_P['themeid']);
        if ($_P['op'] == 'searchtuan') {

            $result = Record::searchtuan($baseinfo['config'], $themeid);

            $tuanlistnew = array();
            if (!empty($result['tuanlist'])) {
                foreach ($result['tuanlist'] as $index => $row) {
                    if ($row['pid'] == $row['id']) {
                        $tuanlist_index = $index;
                    }
                    $tuanid = $row['id'] + 10000;
                    $tuanlistnew[$index]['name'] = $row['username'] . "【" . $row['mobile'] . "】已有" . $row['renshu'] . "人 团号" . $tuanid;
                    $tuanlistnew[$index]['value'] = $row['id'];
                }
            }
            $result['tuanlist'] = $tuanlistnew;
            return_json(0, '', $result);
        }
        //多选分类数据处理
        if ($_G['ispost'] && $baseinfo['config']['shopstype'] == 8 && $baseinfo['config']['shops'] && $_P['op'] == 'save' && $baseinfo['config']['form_five_qty'] == 1) {
            //获取当前操作的订单
            if ($_P['option']) {
                $tmp_option = explode(',', rtrim($_P['option'], ','));
                if (is_array($tmp_option)) {
                    $recordid = $_P['id'];
                    $tmp_record_item = db_get(t_record, ['id' => $recordid, 'themeid' => $themeid]);
                    if ($tmp_record_item) {
                        //取出历史数据
                        $record_option = $tmp_record_item['option'];
                        $tmp_record_option = explode(',', rtrim($record_option, ','));
                        $diff_arr_add = array_diff($tmp_option, $tmp_record_option);//变动的项
                        $diff_arr_del = array_diff($tmp_record_option, $tmp_option);//取消的项
                        //新增项减少库存
                        if ($diff_arr_add && is_array($diff_arr_add)) {
                            foreach ($diff_arr_add as $k1 => $v1) {
                                $check_item = db_get(t_form_five_user_flag, ['order_id' => $recordid, 'form_item_id' => $v1, 'user_id' => $tmp_record_item['uid'], 'themeid' => $themeid]);
                                if (!$check_item) {
                                    db_insert(t_form_five_user_flag, ['order_id' => $recordid, 'form_item_id' => $v1, 'user_id' => $tmp_record_item['uid'], 'themeid' => $themeid]);
                                }
                            }
                        }
                        //修改项增加库存
                        if ($diff_arr_del && is_array($diff_arr_del)) {
                            foreach ($diff_arr_del as $k2 => $v2) {
                                $check_item = db_get(t_form_five_user_flag, ['order_id' => $recordid, 'form_item_id' => $v2, 'user_id' => $tmp_record_item['uid'], 'themeid' => $themeid]);
                                if ($check_item) {
                                    db_delete(t_form_five_user_flag, ['order_id' => $recordid, 'form_item_id' => $v2, 'user_id' => $tmp_record_item['uid'], 'themeid' => $themeid]);
                                }
                            }
                        }
                    }
                }
            }
        }
        $result = Fans::W_orderedit($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);

        if ($result['error'] == 1) {
            return_json(1, $result['msg']);
        } else {
            $level = $result['level'];
            $config = $result['config'];
            $theme = $baseinfo['theme'];
            $system = $baseinfo['system'];
            $addresstype = $config['addresstype'];
            $shopstype = $config['shopstype'];
            $maxcountall = $config['maxcountall'];
            $record = $result['record'];
            $tuanlist = $result['tuanlist'];
            $wlist = $result['wlist'];
            $jubf = $result['jubf'] = $baseinfo['jubf'];
            $jishu = $result['jishu'] = $baseinfo['jishu'];
            $formoption = $config['options'];
            $selectedArr = $config['selectedArr'];
            $tuanindex = $result['tuanlist_index'];
            $windex = $result['wlist_index'];

            //多选分类数据处理
            if (!$_G['ispost'] && $config['shopstype'] == 8 && $config['shops']) {
                $selectedshops = $result['record']['shops'];
                if ($selectedshops) {
                    //数据兼容处理
                    if (strstr($selectedshops, '|')) {
                        $selectedshops = rtrim($selectedshops, '|');
                        $selectedshops = explode("|", $selectedshops);
                    }
                    if (is_string($selectedshops) && strstr($selectedshops, ',')) {
                        $selectedshops = rtrim($selectedshops, ',');
                        $selectedshops = explode(",", $selectedshops);
                    }

                }
                $dx_cate = $baseinfo['config']['dx_cate'];
                if ($dx_cate) {
                    foreach ($dx_cate as $k => $v) {
                        foreach ($v['list'] as $kk => $vv) {
                            if ($vv['is_default'] == 1) {
                                $dx_cate[$k]['list'][$kk]['checked'] = 1;
                            }
                            foreach ($selectedshops as $kkk => $vvv) {
                                if ($vv['name'] == $vvv || $vv['id'] == $vvv) {
                                    $dx_cate[$k]['list'][$kk]['checked'] = 1;
                                }
                            }
                            //开启限购
//                            if ($baseinfo['config']['form_five_qty'] && !in_array($vv['id'],$selectedshops)){
//                                $item_can_show = Common::getFormFIveAndLimitBuyCanShowByItemId($baseinfo['config'],$themeid,$vv['id']);
//                                if (!$item_can_show){
//                                    unset($dx_cate[$k]['list'][$kk]);
//                                }
//                            }
                        }
                    }
                }
            }

            if ($record) {
                if ($record['option']) {
                    $formoptiontip = $record['formoptiontip'];
                    $formradiovalue = $record['formradiovalue'];
                }
                if ($record['address']) {
                    $addressoptiontip = $record['addressoptiontip'];
                }
                if ($record['datetime']) {
                    $formdate = $record['formdate'];
                    $formdatetip = $record['formdatetip'];
                }
            }
            if ($_G['ispost']) {
                return_json(0, '', $result);
            } else {
                $return_clicent = get_defined_vars();
                $return_clicent = get_defined_vars();
                return view('fcworker/fc_orderedit', $return_clicent);
            }
        }
    }

    public function X_mypay()
    {
        try {
            global $_P, $_G;

            extract($this->Isworker());
            if ($config['examplestyle'] == 1 && $_P['example'] == true) {
                $result = Worker::w_example($system, $theme, $config, $myworker);
                $order = $result;
                $themyorder = array(
                    'realfee' => $order['realfee'],
                    'uniontid' => $order['uniontid'],
                    'transaction_id' => $order['transaction_id'],
                );
                $themyrecord = array(
                    'username' => $order['username'],
                    'mobile' => $order['mobile'],
                );
                $fans['avatar'] = $order['avatar'];
                $themyrecord['mobile'] = mb_substr($themyrecord['mobile'], 0, 3, 'utf-8') . '****' . mb_substr($themyrecord['mobile'], $usernamelen - 4, 4, 'utf-8');
                $worker = db_find("SELECT * FROM " . tablename(t_worker) . " WHERE uid = '{$_G['member']['uid']}'");
                $url = "/" . createMobileUrl('w_index', array('themeid' => $themeid));

            } else {
                //未支付的进行较验是否已支付
                Order::checkorder($themeid, $config, $system);

                if (empty($_P['order_id'])) {
                    $themyrecord = Record::getLastPayRecord($_G['member']['uid'], $themeid);
                } else {
                    $themyrecord = Record::getByIdUid($_G['member']['uid'], $_P['order_id']);
                }

                if (!empty($themyrecord)) {
                    if ($themyrecord['type'] == 1) {
                        $recordid = $themyrecord['pid'];
                    } else {
                        $recordid = $themyrecord['id'];
                        $isleader = 1;
                    }
                    $themyrecordid = $recordid + 1000;
                } else {
                    return return_msg('未查到您的付款定单');
                }
                if ($themyrecord['status'] == 3) {
                    $themyorder['uniontid'] = "线下支付定单";
                    $themyorder['realfee'] = $themyrecord['fee'];
                } else {
                    $themyorder = Order::getPayOrderByRIdZhifude($themyrecord['id']);
                }
                $themyrecord['mobile'] = mb_substr($themyrecord['mobile'], 0, 3, 'utf-8') . '****' . mb_substr($themyrecord['mobile'], $usernamelen - 4, 4, 'utf-8');

                $worker = db_find("SELECT * FROM " . tablename(t_worker) . " WHERE uid = '{$themyrecord['workerid']}'");

                $shareinfo = Theme::getshareinfo($system, $theme, $config, $fans, $shopname, $workername, $recordid);

                $themyorder['realfee'] = sprintf("%.2f", $themyorder['realfee']);


                //读取此用户的所有订单
                $allrecord = Record::getLastGroupByOpenidAllhexiao($_G['openid'], $themeid, "id,fee,status,hexiaoerm", $isorder);
                if ($config['shopstype5'] == 1) {
                    $options = str_replace("|", "','", $themyrecord['option']);
                    $tiaojian = " and name in ('" . $options . "')";
                }

                foreach ($allrecord as $index => $item) {
                    if ($item['id'] == $themyrecord['id']) {
                        $allrecord[$index]['bt_status'] = 'on';
                    } else {
                        $allrecord[$index]['bt_status'] = '';
                    }
                    $allrecord[$index]['bt_name'] = '第' . ($index + 1) . "个订单";
                }
            }
            $theme['jubf'] = empty($theme['jubf']) ? mb_substr($theme['title'], 0, 12, 'utf-8') : $theme['jubf'];

            $confignnew = array();
            $confignnew['zhuandantxt'] = $config['zhuandantxt'];
            $confignnew['zhuandantips'] = $config['zhuandantips'];
            $confignnew['addresstxt'] = $config['province'] . $config['city'] . $config['district'] . $config['addresstxt'];
            $confignnew['zhuandanbegintime'] = date('Y-m-d', $config['zhuandanbegintime']);
            $confignnew['zhuandanendtime'] = date('Y-m-d', $config['zhuandanendtime']);
            if (intval($_P['showimg']) == 1 && !empty($config['zhuandanimg'])) {
                $zhuandanimg = $config['zhuandanimg'];
            } else {
                $zhuandanimg = "";
            }
            $themenew = array(
                'jubf' => $theme['jubf'],
                'mobile' => $theme['mobile'],
            );

            $is_lz_game = 0;
            $lz_game_pay_card_img = '';
            $jump_url = '';
            $koi_page_path = '';
            $lucky_five_koi_icon = '';

            $fanstemp = Fans::getworkerid_fromuid($themeid, $fans);
            $workerid = $fanstemp['workerid'];
            $fromuid = $fanstemp['fromuid'];

//游戏信息判断
            if ($system['is_lz_game']) {
                $config = Theme::getConfig($themeid);
                $is_lz_game = !empty($config['lz_game_img']) && !empty($config['five_themeid']) ? 1 : 0;
                $lz_game_pay_card_img = $config['lz_game_pay_card_img'];
                $jump_url = '/pages/index/index?softname=' . MODULE_NAME . '&themeid=' . $themeid . '&softkey=' . $theme['softkey'] . '&fromuid=' . $fromuid . '&workerid=' . $workerid;
            }
            $five_theme = Game::getThemeListByType('five_koi', $themeid);
            if ($five_theme['type_theme_total'] > 0) {
                $new_theme = Theme::getThemeById($five_theme['type_theme_list'][0]['id']);
                $xcxurl = '/pages/index/index?softname=' . MODULE_NAME . '&themeid=' . $new_theme['id'] . '&softkey=' . $new_theme['softkey'] . '&fromuid=' . $fromuid . '&workerid=' . $workerid;
                $koi_page_path = $xcxurl;
                $lucky_five_koi_icon = $config['pay_to_koi'];
            }
//判断支付凭证页面是否显示五连抽弹窗

            $config2 = Theme::getConfig($config['five_themeid']);

            $result = array();
            $show_koi_five_lucky = $result['show_koi_five_lucky'] = Koi::getShowKoiFiveLucky($config2, $config['five_themeid'], $_G['member']['uid']);

            $jishu = $result['jishu'] = Worker::getjishu($theme, $system);
            $themyorder = $result['themyorder'] = $themyorder;
            $themyrecord = $result['themyrecord'] = $themyrecord;
            $worker = $result['worker'] = $worker;
            $config = $result['config'] = $confignnew;
            $shareinfo = $result['shareinfo'] = $shareinfo;
            $zhuandanimg = $result['zhuandanimg'] = $zhuandanimg;
            $fans = $result['fans'] = $fans;
            $theme = $result['theme'] = $themenew;
            $allrecord = $result['allrecord'] = $allrecord;

            $is_lz_game = $result['is_lz_game'] = $is_lz_game;//是否开启了定制游戏
            $lz_game_pay_card_img = $result['lz_game_pay_card_img'] = $lz_game_pay_card_img;//顶部图片
            $jump_url = $result['jump_url'] = $jump_url;
            $koi_page_path = $result['koi_page_path'] = $koi_page_path;
            $lucky_five_koi_icon = $result['lucky_five_koi_icon'] = $lucky_five_koi_icon;

            $return_clicent = get_defined_vars();
            if ($_G['companyname'] && $_G['companyname'] == '飞驰软件') {
                $return_clicent = get_defined_vars();
                return view('fcpdd/paysuccess', $return_clicent);
            } else {
                $return_clicent = get_defined_vars();
                return view('base/paysuccess01', $return_clicent);
            }
        } catch (Exception $e) {
            var_dump($e->getmessage());
            die();
        }

    }

    public function X_example()
    {
        global $_P, $_G;
        $baseinfo = $this->Isworker();
        if ($baseinfo['config']['examplestyle'] == 1) {
            $url = $_G['siteroot'] . createMobileUrl('w_example', array("themeid" => $baseinfo['theme']['id']));
            echo "<script language='javascript' type='text/javascript'>";
            echo "window.location.href='$url';";
            echo "</script>";
            exit;
        }
        $example_style = $baseinfo['config']['examplestyle'];
        $result = Worker::w_example($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        $result['transaction_id'] = mb_substr($result['transaction_id'], 0, 16, 'utf-8') . "******" . mb_substr($result['transaction_id'], 22, 6, 'utf-8');
        $result['uniontid'] = mb_substr($result['uniontid'], 0, 16, 'utf-8') . "******" . mb_substr($result['uniontid'], 22, 6, 'utf-8');

        if ($baseinfo['config']['isexampleqr'] != 2) {
            if (!empty($result['workerid'])) {
                $fansinfo = db_find('SELECT * FROM ' . tablename(t_fans) . '
                WHERE themeid = :themeid AND uid = :uid', array(':themeid' => $baseinfo['themeid'], ':uid' => $result['workerid']));
                if (empty($fansinfo['poster_qrcode'])) {
                    $scene = MODULE_NAME . "-" . $baseinfo['themeid'] . "-" . $result['workerid'] . "-" . $baseinfo['theme']['softkey'];
                    $result['qrcode'] = Poster::CreateScene($baseinfo['system'], $scene, $baseinfo['config'], 'pages/index/index');
                } else {
                    $result['qrcode'] = $fansinfo['poster_qrcode'];
                }
            }
        }
        if ($result['error'] == 1) {
            return_json(1, $result['msg']);
        } else {
            $order = $result;
            $theme = $baseinfo['theme'];
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            $return_clicent = get_defined_vars();
            return view('fcworker/fc_example', $return_clicent);
        }
    }

    public function X_report()
    {
        global $_P, $_G;
        $wx = $_G['platform']['jssdkconfig'];
        $baseinfo = $this->Isworker();
        $theme = $baseinfo['theme'];
        $result = Worker::w_report($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);

        if ($result['error'] == 1) {
            return_json(1, $result['msg']);
        } else {
            $themeid = $baseinfo['theme']['id'];
            $day = date('d');
            if (strlen($day) < 1) {
                $day = '0' . $day;
            }

            $allcompany = $result['allcompany'];
            $mycompany = $result['mycompany'];
            $workertips = $result['workertips'];
            $team = $result['team'];

            if (count($allcompany) > 1 || count($mycompany) > 1 || count($team) > 1) {
                if ($day == substr($allcompany[1]['riqi'], 3, 2)) {
                    array_splice($allcompany, 0, 1);
                }
                if ($day == substr($mycompany[1]['riqi'], 3, 2)) {
                    array_splice($mycompany, 0, 1);
                }
                if ($day == substr($team[1]['riqi'], 3, 2)) {
                    array_splice($team, 0, 1);
                }
            }


            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            $return_clicent = get_defined_vars();
            return view('fcworker/fc_report', $return_clicent);
        }
    }

//    客资电话
    public function X_fans()
    {
        global $_P, $_G;
        $wx = $_G['platform']['jssdkconfig'];
        $baseinfo = $this->Isworker();
        //删除重复员工
        $themeid = intval($_P['themeid']);
        Fans::WorkerDeleteChongfu($themeid);
        $theme = $baseinfo['theme'];
        $system = $baseinfo['system'];
        $result = Fans::W_fans($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        if ($result['error'] == 1) {
            return_json(1, $result['msg']);
        } else {
            $themeid = $baseinfo['theme']['id'];
            $scan = isset($_P['scan']) ? $_P['scan'] : 0;
            $page = $result['page'];
            $hasNext = $result['hasNext'];
            $info = $result['info'];
            $list = $result['list'];
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            if ($_G['ispost']) {
                $append_html = '';
                foreach ($list as $key => $item) {

//                    peoPle
                    $append_html .= '<div class="peoPle">' . PHP_EOL;
//                      peopleTime
                    $append_html .= '<div class="peopleTime">' . $item['sid'] . '.' . $item['addtime'] . '</div>' . PHP_EOL;
//                      peopleInfor
                    $append_html .= '<div class="peopleInfor">' . PHP_EOL . '<div class="peopleImg">' . PHP_EOL . '<img src="' . $item['avatar'] . '">' . PHP_EOL . '<div class="teamNum">UID:' . $item['uid'] . '</div>' . PHP_EOL . '</div>' . PHP_EOL . '<div class="peopleTxt">' .
                        '<h2>' . $item['username'] . '</h2>' . PHP_EOL .
                        '<p>昵称：' . $item['nickname'] . '</p>' . PHP_EOL .
                        '<p>' . $item['workernameall'] . '</p>' . PHP_EOL;
                    $append_html .= '</div>' . PHP_EOL;
                    $append_html .= '<a href="tel:' . $item['mobile'] . '" class="telBtn"></a>' . PHP_EOL . '</div>' . PHP_EOL;
                    //information
                    $append_html .= '<div class="information">' . PHP_EOL;
                    foreach ($item['moreinfo'] as $k => $v) {
                        $append_html .= '<p>' . $v . '</p>' . PHP_EOL;
                    }
                    $append_html .= '</div>' . PHP_EOL;
                    //controlBox
                    $append_html .= '<div class="controlBox">' . PHP_EOL . '<span class="contBtn">更多信息</span>' . PHP_EOL;
                    $append_html .= '</div>' . PHP_EOL . '</div>' . PHP_EOL;
                }
                $result['append_html'] = $append_html;
                return_json(0, '', $result);
            } else {
                $return_clicent = get_defined_vars();
                return view('fcworker/fc_fans', $return_clicent);
            }

        }
    }

    /**
     * Desc:表单收集
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/8/12 18:23
     */
    public function X_otherForm()
    {
        global $_P, $_G;
        $wx = $_G['platform']['jssdkconfig'];
        $baseinfo = $this->Isworker();
        $soft = $_P['soft'];
        $themeid = intval($_P['themeid']);
        $op = $_P['op'] ? $_P['op'] : 'display';
        $search_data = $_P['searchtxt'] ? $_P['searchtxt'] : '';
        $select_workerid = $_P['select_workerid'] ? $_P['select_workerid'] : 0;
        $worker_list = [];
        if ($baseinfo['myworker']['level'] == 1 || $baseinfo['myworker']['level'] == 2) {
            $worker_list = OtherForm::getSJWorkerList($_P['themeid'], $baseinfo['myworker']['company']);
            array_unshift($worker_list, ['uid' => 0, 'username' => '全部']);
        }
        $result = OtherForm::adminOtherForm($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        $result['workers'] = $worker_list;
        $result['jubf'] = $baseinfo['jubf'];
        $result['jishu'] = $baseinfo['jishu'];
        $result['level'] = $baseinfo['myworker']['level'];

        extract($result);
        if ($_G['ispost'] && $op2 != 'search') {
            $append_html = '';
            foreach ($list as $key => $item) {

//                    peoPle
                $append_html .= '<div class="peoPle">' . PHP_EOL;
//                      peopleTime
                $append_html .= '<div class="peopleTime" style="display: flex;flex-direction: row;justify-content: space-between;">';

                $append_html .= '<div>';
                if ($item['order_info'] == '未支付') {
                    $append_html .= '<span style="background: red;color: #ffffff;padding: 3px;border-radius: 3px;">' . $item['order_info'] . '</span>' . $item['created_at'] . '</div>';
                } else {
                    $append_html .= '<span style="background: #07c160;color: #ffffff;padding: 3px;border-radius: 3px;">' . $item['order_info'] . '</span>' . $item['created_at'] . '</div>';
                }
                $append_html .= '<div>' . $item['workername'] . '</div>';
                $append_html .= '</div>' . PHP_EOL;
//                      peopleInfor
                $append_html .= '<div class="peopleInfor">' . PHP_EOL . '<div class="peopleImg">' . PHP_EOL . '<img src="' . $item['avatar'] . '">' . PHP_EOL . '<div class="teamNum">UID:' . $item['uid'] . '</div>' . PHP_EOL . '</div>' . PHP_EOL . '<div class="peopleTxt">' .
                    '<h2>' . $item['nickname'] . '</h2>' . PHP_EOL .
                    '<p>姓名：' . $item['username'] . '</p>' . PHP_EOL;
                $append_html .= '</div>' . PHP_EOL;
                $append_html .= '<a href="tel:' . $item['mobile'] . '" class="telBtn"></a>' . PHP_EOL . '</div>' . PHP_EOL;
                //information
                $append_html .= '<div class="information">' . PHP_EOL;
                foreach ($item['moreinfo'] as $k => $v) {
                    $append_html .= '<p>' . $v . '</p>' . PHP_EOL;
                }
                $append_html .= '</div>' . PHP_EOL;
                //controlBox
                $append_html .= '<div class="controlBox">' . PHP_EOL . '<span class="contBtn">更多信息</span>' . PHP_EOL;
                $append_html .= '</div>' . PHP_EOL . '</div>' . PHP_EOL;
            }
            $result = [];
            $result['hasNext'] = $hasNext;
            $result['append_html'] = $append_html;
            return_json(0, '', $result);
        } else {
            $return_clicent = get_defined_vars();
            return view('fcworker/fc_fans_other_info', $return_clicent);
        }
    }

//    团长排名
    public function X_ranktuan()
    {
        global $_P, $_G;
        $wx = $_G['platform']['jssdkconfig'];
        $baseinfo = $this->Isworker();
        $theme = $baseinfo['theme'];
        $system = $baseinfo['system'];

        $op = $_P['op'];
        $show = $_P['show'] ? $_P['show'] : '';
        $page = $page_index = max(1, intval($_P['page']));
        $page_size = 20;
        $page_start = ($page_index - 1) * $page_size;
        $hasNext = true;

        $result = Worker::w_ranktuan($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker'], $page_start, $page_size);
        if ($result['error'] == 1) {
            return return_msg($result['msg']);
        } else {
            $paixu = !empty($_P['paixu']) ? $_P['paixu'] : 0;
            $themeid = $baseinfo['theme']['id'];
            $ranktuan = $result['ranktuan'];
            $rankfans = $result['rankfans'];
            $page_total = $result['page_total'];
            if ($page >= $page_total) {
                $hasNext = false;
            }
            $sortlist = ['成交数排名', '推荐数排名', '转发量排名', '浏览量排名'];
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            if ($_G['ispost']) {
                $format_data = [];
                $temp_html_taun = '';
                $temp_html_fans = '';
                if ($op == 'ranktuan') {
                    $sort = (($page - 1) * 20);
                    foreach ($ranktuan as $key => $val) {
                        $new_sort = $sort + ($key + 1);
                        $url = '/' . createMobileUrl("X_group", array("themeid" => $themeid)) . "&id=" . $val['pid'];
                        $temp_html_taun .= '<tr class="new_tr">' . PHP_EOL . '<td>' . $new_sort . '</td>' . PHP_EOL . '<td>' . PHP_EOL . '<img src="' . $val['avatar'] . '" class="td-img">' . PHP_EOL;
                        $temp_html_taun .= '</td>' . PHP_EOL . '<td>' . $val['username'] . '</td>' . PHP_EOL . '<td>' . $val['idnew'] . '</td>' . PHP_EOL;
                        $temp_html_taun .= '<td><a href="' . $url . '"><span style="color: #a7a7a7;">' . $val['tuannum'] . '</span></a></td>' . PHP_EOL;
                        $temp_html_taun .= '<td><a href="' . $url . '"><span style="color: #a7a7a7;">明细</span></a></td>' . PHP_EOL;
                        $temp_html_taun .= '</tr>';
                    }
                }
                if ($op == 'rankfans') {
                    $sort = (($page - 1) * 20);
                    foreach ($rankfans as $key => $val) {
                        $new_sort = $sort + ($key + 1);
                        if (!$val['avatar'] || $val['avatar'] == '') {
                            $val['avatar'] = 'https://css2020.yixuan.net/2020css/yx2020/images/question.png';
                        }
                        $temp_html_fans .= '<tr class="new_tr">' . PHP_EOL . '<td>' . $new_sort . '</td>' . PHP_EOL . '<td>' . PHP_EOL . '<img src="' . $val['avatar'] . '" class="td-img">' . PHP_EOL;
                        $temp_html_fans .= '</td>' . PHP_EOL . '<td>' . $val['name'] . '</td>' . PHP_EOL . '<td>' . $val['scansum'] . '</td>' . PHP_EOL . '<td>' . $val['forward'] . '</td>' . PHP_EOL;
                        $temp_html_fans .= '<td>' . $val['tuijian'] . '</td>' . PHP_EOL . '<td>' . $val['responsum'] . '</td>' . PHP_EOL . '</tr>';
                    }
                }

                return_json(0, '', ['hasNext' => $hasNext, 'page_total' => $page_total, 'ranktuan' => $temp_html_taun, 'rankfans' => $temp_html_fans]);
            } else {
                $return_clicent = get_defined_vars();
                return view('fcworker/fc_ranktuan', $return_clicent);
            }

        }
    }

//    线下订单录入
    public function xInput()
    {
        return self::X_input();
    }

    public function X_input()
    {
        global $_P, $_G;
        $system = $this->getsystem();
        $themeid = intval($_P['themeid']);
        $theme = Theme::getThemeById($themeid);
        $config = Theme::getConfig($themeid);
        if ($config['presale']['presalePrice'] > 1 && TIMESTAMP > $config['yukuantime']) {
            $system['bottom_jiage'] = $config['presale']['presalePrice'] - 1;
        }
        $wx = $_G['platform']['jssdkconfig'];
        $fans = $this->checkuser();
        $method = isset($_P['method']) ? $_P['method'] : '';
        $myworker = Worker::getThemeWorkerByOpenid($_G['openid'], $themeid, 1);
        if (empty($_P['op']) && ($system['bottom_jiage'] > 0)) {
            $group_name = Record::getGroupName($config);
            $return_clicent = get_defined_vars();
            return view('fcworker/fc_input', $return_clicent);
            return;
        }

        if ($_P['op'] == 'bangding') {
            try {
                $result = W_Input::bangding($system, $config, $fans);
            } catch (Exception $e) {
                yxlog($e->getmessage());
            }
            if ($result['error'] == 1) {
                if ($_G['ispost']) {
                    return_json(1, $result['msg']);
                } else {
                    return return_msg($result['msg']);
                }

            } else {
                if ($_G['ispost']) {
                    return_json(0, '', $result);
                } else {
                    $url = $_G['siteroot'] . createMobileUrl('index', array('themeid' => $themeid));
                    echo "<script language='javascript' type='text/javascript'>";
                    echo "window.location.href='$url';";
                    echo "</script>";
                    exit;
                }
            }
        } elseif ($_P['op'] == "getinfo" || $_P['op'] == "reset") {
            $recordid = $_P['recordid'];
            $result = W_Input::input($system, $theme, $config, $myworker);
            $_P['op'] = "getinfo";
            $tmp_form_five_qty = $config['form_five_qty'];
            $config = $result['config'];
            if ($tmp_form_five_qty) {
                $config['form_five_qty'] = $tmp_form_five_qty;
            }
            $baseinfo = array();
            $baseinfo['config'] = $config;
            $baseinfo['jubf']['title'] = '定单确认';
            $baseinfo['jubf']['banquan'] = '';
            $baseinfo['jishu'] = '';
        } elseif ($_P['op'] == 'save') {
            $baseinfo = $this->Isworker();
            $result = W_Input::input($system, $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);

            $sharedata = array(
                'themeid' => $themeid,
                'op' => 'getinfo',
                'recordid' => $result['record']['id'],
            );
            if ($system['gongzhong'] == '1') {
                $domaintxt = $system['domainhead1'];
            } else {
                $domaintxt = DOMAIN0;
            }
            $inputurl = $_G['url_scheme'] . $domaintxt . "/" . createMobileUrl('x_input', $sharedata);
            $inputurl = QRURLNEW . urlencode($inputurl);
        } else {
            $baseinfo = $this->Isworker();
            $result = W_Input::input($system, $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
            $config = $result['config'];
        }
        if ($result['error'] == 1) {
            if ($_G['ispost']) {
                return_json(1, $result['msg']);
            } else {
                return return_msg($result['msg']);
            }

        } else {
            $shopstype = $config['shopstype'];
            $level = $result['level'];
            $record = $result['record'];
            $formoption = $config['options'];
            $feelistoption = $result['feelist'];
            $feelisttip = $feelistoption[0]['fullname'];
            $addressoption = $config['addressoptions'];
            $selectedArr = $result['config']['selectedArr'];
            $dx_cate = $result['config']['shopsoptions'];
            if ($_P['op'] == "getinfo") {
                $addresstype = $config['addresstype'];
                $shopstype = $config['shopstype'];
                $formradiovalue = $formoptiontip = $record['option'];
                $addressoptiontip = $record['address'];
                $qrimg = $result['qrimg'];
                $username = $result['username'];
                $mobile = $result['mobile'];
                //判断启用多选分类
                if ($shopstype == 8 && $record['option'] && $dx_cate) {
                    $option_arr = explode(',', rtrim($record['option'], ','));
                    foreach ($dx_cate as $k => $v) {
                        $tmp_list = $v['list'];
                        foreach ($tmp_list as $k1 => $v1) {
                            if (!in_array($v1['id'], $option_arr)) {
                                unset($dx_cate[$k]['list'][$k1]);
                            }
                        }
                    }
                }
            }
            if ($record && $record['datetime']) {
                $formdate = $formdatetip = $record['datetime'];
            }
            if ($inputurl) {
                $result['inputurl'] = $inputurl;
            }
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            if ($_G['ispost']) {
                return_json(0, '', $result);
            } else {
                if ($_P['op'] == "getinfo") {
                    $sharedata = array(
                        'themeid' => $themeid,
                        'op' => 'getinfo',
                        'recordid' => $result['record']['id'],
                    );
                    if ($system['gongzhong'] == '1') {
                        $domaintxt = $system['domainhead1'];
                    } else {
                        $domaintxt = DOMAIN0;
                    }
                    $inputurl = $_G['url_scheme'] . $domaintxt . "/" . createMobileUrl('x_input', $sharedata);
                    $inputurl = QRURLNEW . urlencode($inputurl);
                }
                $return_clicent = get_defined_vars();
                return view('fcworker/fc_input', $return_clicent);
            }

        }
    }

//    基本设置
    public function X_setbase()
    {
        global $_P, $_G;
        $baseinfo = $this->Isworker();
        $theme = $baseinfo['theme'];
        $system = $baseinfo['system'];
        $result = Worker::w_setbase($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        if ($result['error'] == 1) {
            return_json(1, $result['msg'], '');
        } else {
            $theme = $baseinfo['theme'];
            $theme['endtime'] = date("Y-m-d H:i", $theme['endtime']);
            $themeid = $baseinfo['theme']['id'];
            $config = $baseinfo['config'];
            $system = $baseinfo['system'];
            $status = $theme['status'];
            $tuanmode = $config['tuanmode'];
            $zhuandanbegintime = date("Y-m-d", $config['zhuandanbegintime']);
            $zhuandanendtime = date("Y-m-d", $config['zhuandanendtime']);
            $result['jubf'] = $baseinfo['jubf'];
            $jishu = $result['jishu'] = $baseinfo['jishu'];
            if ($_G['ispost']) {
                return_json(0, $result['msg'], '');
            } else {
                $return_clicent = get_defined_vars();
                return view('fcworker/fc_setbase', $return_clicent);
            }

        }
    }

//    虚拟数据
    public function X_setxuni()
    {
        global $_P, $_G;
        $baseinfo = $this->Isworker();
        $theme = $baseinfo['theme'];
        $system = $baseinfo['system'];
        $result = Worker::w_setxuni($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        if ($result['error'] == 1) {
            return_json(1, $result['msg'], '');
        } else {
            $themeid = $baseinfo['theme']['id'];
            $config = $result['config'];
            $touxiang = $config['touxiang'];
            $result['jubf'] = $baseinfo['jubf'];
            $jishu = $result['jishu'] = $baseinfo['jishu'];
            if ($_G['ispost']) {
                return_json(0, $result['msg'], '');
            } else {
                $return_clicent = get_defined_vars();
                return view('fcworker/fc_setxuni', $return_clicent);
            }
        }
    }

//    手机端设置
    public function X_setmobile()
    {
        global $_P, $_G;
        $baseinfo = $this->Isworker();
        $theme = $baseinfo['theme'];
        $system = $baseinfo['system'];
        $result = Worker::w_setmobile($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        if ($result['error'] == 1) {
            return_json(1, $result['msg'], '');
        } else {
            $themeid = $baseinfo['theme']['id'];
            $config = $baseinfo['config'];
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            if ($_G['ispost']) {
                return_json(0, $result['msg'], '');
            } else {
                $return_clicent = get_defined_vars();
                return view('fcworker/fc_setmobile', $return_clicent);
            }
        }
    }

//    其他设置
    public function X_setother()
    {
        global $_P, $_G;
        $baseinfo = $this->Isworker();
        $theme = $baseinfo['theme'];
        $system = $baseinfo['system'];
        $result = Worker::w_setother($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        if ($result['error'] == 1) {
            return_json(1, $result['msg'], '');
        } else {
            $themeid = $baseinfo['theme']['id'];
            $config = array_merge($result['config'], $baseinfo['config']);
            $radio = $result['radio'];
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            if ($_G['ispost']) {
                return_json(0, $result['msg'], '');
            } else {
                $return_clicent = get_defined_vars();
                return view('fcworker/fc_setother', $return_clicent);
            }
        }
    }

//    小程序专用
    public function W_rank()
    {
        global $_P, $_G;
        $baseinfo = $this->Isworker();
        $result = Fans::w_rank($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        if ($result['error'] == 1) {
            return return_msg($result['msg']);
            die();
        } else {
            $paixu = $_P['paixu'] ? $_P['paixu'] : 'record';
            $companylist = $result['companylist'];
            $companytoday = $result['companytoday'];
            $teamlist = $result['teamlist'];
            $teamtoday = $result['teamtoday'];
            $workerlist = $result['workerlist'];
            $workertoday = $result['workertoday'];
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            $return_clicent = get_defined_vars();
            return view('fcworker/fc_rank', $return_clicent);
        }
    }

    public function X_showqr()
    {
        global $_P, $_G;
        extract($this->Isworker());
        $result = Worker::show_other_qr($system, $theme, $config, 'h5');
        if ($result['error'] == 1) {
            return_json(1, $result['msg']);
        } else {
            $result['jubf'] = $jubf;
            $result['jishu'] = $jishu;
            return_json(0, '', $result);
        }
    }

    public function X_ltVerif()
    {
        require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
        require_once get_path('plugin/lottery/core/model.php');
        global $_P, $_G;
        $baseinfo = $this->Isworker();
        $op = isset($_P['op']) ? $_P['op'] : 'display';
        if (!$baseinfo) {
            if ($op == 'display') {
                return return_msg('非员工无法访问');
                die();
            } elseif ($op == 'sure_verify' && $_G['ispost']) {
                return_json(1, '非员工无法访问', '');
            }

        }
        $themeid = $baseinfo['theme']['id'];
        $openid = $_G['openid'];
        $uid = $_P['fromuid'];
        $code = $_P['code'];
        $config = $baseinfo['config'];

        $res = db_get(t_fans, ['themeid' => $themeid, 'openid' => $openid]);
        if ($res && $res['uid']) {
            $workerid = $res['uid'];
        } else {
            $relation = Relation::getByThemeId($baseinfo['theme']['id'], $_G['openid']);
            $workerid = $relation['workerid'];
        }
        if ($op == 'display') {
            $lt_flag = \LotteryModel::getLtFlagAndPrizeInfoByWhere($themeid, $uid, $code);
            $info = [
                'img' => $lt_flag['small_img'],
                'gift_title' => $lt_flag['title'] . '-' . $lt_flag['name'],
                'username' => $lt_flag['username'],
                'mobile' => $lt_flag['mobile'],
                'f_id' => $lt_flag['f_id'],
                'uid' => $uid,
                'themeid' => $themeid,
                'notice' => ''
            ];
            //判断唯一性兑换
            if (!$baseinfo['config']['yx_lt_convert_only']) {
                $user_chekced_falg = \LotteryModel::getUserFlags($themeid, $uid, 4);
                if ($user_chekced_falg > 0) {
                    $info['notice'] = '已核销其他奖品，当前继续核销';
                }
            }
            if ($lt_flag && $lt_flag['status'] == 4) {
                $r = Worker::getWokerName($baseinfo['system'], $themeid, $lt_flag['workerid']);
                $workername = $r['workername'];
                $info['notice'] = '由员工[' . $workername . '],于' . $lt_flag['checked_at'] . '完成核销';
            }
            $return_clicent = get_defined_vars();
            return view('fcworker/fc_verif', $return_clicent);
        } elseif ($op == 'sure_verify') {
            if ($_G['ispost']) {
                //判断唯一性兑换
                if (!$baseinfo['config']['yx_lt_convert_only']) {
                    $user_chekced_falg = \LotteryModel::getUserFlags($themeid, $uid, 4);
                    if ($user_chekced_falg > 0) {
                        return_json(1, '已核销其他奖品，当前无法核销', '');
                    }
                }
                $f_id = isset($_P['f_id']) ? intval($_P['f_id']) : 0;
                if (!$f_id) {
                    return_json(1, '核销记录参数缺失', '');
                }
                $item = \LotteryModel::getLtFlagAndPrizeInfo($themeid, $f_id);

                $res = \LotteryModel::editLtFlagItemByWhere($f_id, $themeid, $item['uid'], $workerid);
                if (!$config['yx_lt_convert_only'] && $res) {
                    //修改其他的奖项为失效
                    \LotteryModel::editUserLtFlagLose($uid, $themeid, $item['p_id'], $f_id);
                }
                if (empty($res)) {
                    return_json(1, '该奖品未兑换或已核销，请检查后重试', '');
                } else {
                    return_json(0, '核销成功', '');
                }
            }
        }
    }

    public function X_Gifts()
    {
        global $_P, $_G;
        $baseinfo = $this->Isworker();
        $op = isset($_P['op']) ? $_P['op'] : 'display';
        if (!$baseinfo) {
            if ($op == 'display') {
                return return_msg('非员工无法访问');
                die();
            } elseif ($op == 'sure_verify' && $_G['ispost']) {
                return_json(1, '非员工无法访问', '');
            }

        }
        $themeid = $baseinfo['theme']['id'];
        $openid = $_G['openid'];
        $uid = $_P['fromuid'];
        $f_id = $_P['f_id'];
        $config = $baseinfo['config'];

        $res = db_get(t_fans, ['themeid' => $themeid, 'openid' => $openid]);
        if ($res && $res['uid']) {
            $workerid = $res['uid'];
        } else {
            $relation = Relation::getByThemeId($baseinfo['theme']['id'], $_G['openid']);
            $workerid = $relation['workerid'];
        }
        if ($op == 'display') {
            $item = db_get(t_yyy_gifts_flag, ['themeid' => $themeid, 'id' => $f_id]);
            if (!$item) {
                return return_msg('记录不存在');
            }
            $fans = db_get(t_fans, ['themeid' => $themeid, 'uid' => $item['uid']]);
            $lt_flag = YxGifts::getGiftItem($themeid, $fans, $f_id, $config);
            $info = [
                'img' => $lt_flag['img'],
                'gift_title' => $lt_flag['gift_title'],
                'username' => $lt_flag['username'],
                'mobile' => $lt_flag['mobile'],
                'f_id' => $lt_flag['f_id'],
                'themeid' => $themeid,
                'notice' => ''
            ];
            if ($lt_flag && $lt_flag['status'] == 4) {
                $r = Worker::getWokerName($baseinfo['system'], $themeid, $lt_flag['workerid']);
                $workername = $r['workername'];
                $info['notice'] = '由员工[' . $workername . '],于' . $lt_flag['updated_at'] . '完成核销';
            }
            $return_clicent = get_defined_vars();
            return view('fcworker/fc_gifts', $return_clicent);
        } elseif ($op == 'sure_verify') {
            if ($_G['ispost']) {
                $f_id = $_P['f_id'];
                //修改订单
                $where = ['id' => $f_id, 'themeid' => $themeid, 'status' => 3];
                $data = ['status' => 4, 'workerid' => $workerid];
                $res = YxGifts::editFanGift($where, $data);
                if (empty($res)) {
                    return_json(1, '该礼品未兑换或已核销，请检查后重试', '');
                } else {
                    return_json(0, '核销成功', '');
                }
            }
        }
    }

//公司排名
    public function X_shoprank()
    {
        global $_G, $_P;
        $fans = $this->checkuser();
        $themeid = intval($_P['themeid']);
        $paixu = $_P['paixu'];
        $from = isset($_P['from']) ? $_P['from'] : 'mobile';
        $system = $_G['system'];
        $theme = Theme::getThemeById($themeid);
        $config = Theme::getConfig($themeid);
        $res = Worker::companyRank($theme, $config, $system, $paixu);
        if ($res['error'] == 1) {
            if ($from == 'mobile') {
                return return_msg($res['msg']);
            }
            return_json(1, $res['msg'], '');
        } else {
            if ($_G['ispost']) {
                return_json(0, $res['msg'], $res['data']);
            } else {
                $result = $res['data'];
                extract($result);
                $return_clicent = get_defined_vars();
                return view('fcworker/fc_shoprank', $return_clicent);
            }
        }
    }

//团队排名
    public function X_grouprank()
    {
        global $_G, $_P;
        $fans = $this->checkuser();
        $themeid = intval($_P['themeid']);
        $paixu = $_P['paixu'];
        $do = 'X_grouprank';
        $from = isset($_P['from']) ? $_P['from'] : 'mobile';
        $system = $_G['system'];
        $theme = Theme::getThemeById($themeid);
        $config = Theme::getConfig($themeid);
        $soft = $_P['soft'];
        $res = Worker::teamRank($theme, $config, $system, $paixu);
        if ($res['error'] == 1) {
            if ($from == 'mobile') {
                return return_msg($res['msg']);
            }
            return_json(1, $res['msg'], '');
        } else {
            if ($_G['ispost']) {
                return_json(0, $res['msg'], $res['data']);
            } else {
                $result = $res['data'];
                extract($result);
                $return_clicent = get_defined_vars();
                return view('fcworker/fc_grouprank', $return_clicent);
            }
        }
    }

//个人排名
    public function X_workerrank()
    {
        global $_G, $_P;
        $fans = $this->checkuser();
        $themeid = intval($_P['themeid']);
        $paixu = $_P['paixu'];
        $do = 'X_grouprank';
        $from = isset($_P['from']) ? $_P['from'] : 'mobile';
        $system = $_G['system'];
        $theme = Theme::getThemeById($themeid);
        $config = Theme::getConfig($themeid);
        $soft = $_P['soft'];
        $res = Worker::workerRank($theme, $config, $system, $paixu);
        if ($res['error'] == 1) {
            if ($from == 'mobile') {
                return return_msg($res['msg']);
            }
            return_json(1, $res['msg'], '');
        } else {
            if ($_G['ispost']) {
                return_json(0, $res['msg'], $res['data']);
            } else {
                $result = $res['data'];
                extract($result);
                $return_clicent = get_defined_vars();
                return view('fcworker/fc_workerrank', $return_clicent);
            }
        }
    }


    /**
     * Desc:新短信通知接口
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2023/5/5 14:01
     */
    public function AliSmsNotify()
    {
        global $_P, $_G;
        $system = $_G['system'];
//        yxlog($_P,'阿里短信通知');
        $params = isset($_P['__input']) ? json_decode($_P['__input'][0]) : [];
//        yxlog($params,'阿里短信通知');
        if ($params) {
            if ($params['template_status'] != 'approving') {
                $template_code = $params['template_code'] ? $params['template_code'] : '';
                //审核通过或者拒绝
                Sms::autoCheckSmsTemplate(MODULE_NAME, $system, $template_code);
            }
        }
        return json_encode(['code' => 0, 'msg' => '成功']);
    }

    /**
     * 投诉接口
     */
    public function Complain()
    {
        global $_P, $_G;
        $system = $_G['system'];
        $themeid = $_P['themeid'];
        $op = isset($_P['op']) ? $_P['op'] : 'home';
        $fans = $this->checkuser();

        if ($op == 'home' || $op == 'question' || $op == 'newquestion' || $op == 'homenewquestion') {
            $content = Complain::getTypeList($system, $themeid);
            $content['complain'] = Complain::getComplain($fans, $themeid);
            extract($content);
            $return_clicent = get_defined_vars();
            return view('base/complain', $return_clicent);
        } elseif ($op == 'save') {
            $r = Complain::saveComplain($system, $fans);
            return_json($r['errcode'], $r['errmsg'], array('reply' => $r['reply ']));
        }
    }

    /**
     * Desc:其他表单收集
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/4/20 13:08
     */
    public function OtherForm()
    {
        global $_P, $_G;
        $system = $_G['system'];
        $themeid = $_P['themeid'];
        $op = isset($_P['op']) ? $_P['op'] : 'display';
        $workerid = isset($_P['workerid']) ? $_P['workerid'] : '0';
        $fans = $this->checkuser();
        if ($fans && $themeid) {
            $res = OtherForm::submitCusInfo($system, $themeid, $fans, $workerid, $_P['filed']);
            return_json($res['error'], $res['msg'], $res['data']);
        }
    }

    //扫码退款
    public function X_UserRefund()
    {
        global $_P, $_G;
        $system = $_G['system'];
        $themeid = $_P['themeid'];
        $config = Theme::getConfig($themeid);
        $theme = Theme::getThemeById($themeid);
        $fromuid = isset($_P['fromuid']) ? intval($_P['fromuid']) : 0;
        //查找员工信息
        $workerinfo = db_get(t_worker, ['uid' => $fromuid, 'themeid' => $themeid]);
        if (!$workerinfo) {
            return_json(1, '未找到工作人员信息', '');
        }

        $themyrecord = Record::getAttendByThemeIdAndOpenid($themeid, $_G['openid'], false);
        if (empty($themyrecord)) {
            return_json(1, '未找到您的定单', '');
        }
        //是否限制退款IP，命名为：refund_limit_ip
        $fromuserinfo = db_get(t_fans, ['uid' => $fromuid, 'themeid' => $themeid]);
        if ($fromuserinfo['ip'] != $_G['clientip']) {
            return_json(1, '需到店连接商家内部安全网络方可进行退款', '');
        }
        $opuser = '扫【' . $workerinfo['username'] . '】的码退';
        if ($config['refund_limit_ip'] == 1) {
            return_json(1, '功能未开启，无权操作', '');
        } else if ($config['refund_limit_ip'] == 2) {
            $ret = Record::refund($themyrecord['id'], $themeid, $theme, $system, $config, $opuser);
            if (isset($ret['error'])) {
                $error = 1;
                $msg = $ret['msg'];
                return_json($error, $msg, '');
            } else {
                return_json(1, '退款失败：未知错误', '');
            }
        } else {
            yxlog($themyrecord['username'] . $themyrecord['mobile'] . $opuser, '扫码退款');
            $state = db_update(t_record, array('isrefund' => 7, 'refundtime' => TIMESTAMP), array('id' => $themyrecord['id']));
            $msg = '您的申请退款已提交，等待申核';
            return_json(1, $msg, '');
        }
    }

    //二维码页面
    public function X_refundCode()
    {
        try {
            global $_P, $_G;
            $fans = $this->checkuser();
            $themeid = $_P['themeid'];
            $baseinfo = $this->Isworker();
            //执行更新IP地址
            db_update(t_fans, ['ip' => $_G['clientip']], ['uid' => $_G['member']['uid'], 'themeid' => $themeid]);
            $qr_img = $_G['siteroot'] . createMobileUrl('X_myRefundInfo', array('themeid' => $themeid, 'fromuid' => $_G['member']['uid']));
            $qr_img = QRURLNEW . urlencode($qr_img);
            $op = 'showqr';
            if (empty($baseinfo['myworker']['refunderm'])) {
                $tips = "客户需要退款时，为创造一次和客户见面沟通的机会，了解客户退款的真正原因，再次压单成交；此功能是客户必须到店连接wifi扫码才可以退款；";
            }
            $return_clicent = get_defined_vars();
            return view('fcworker/fc_refund', $return_clicent);
        } catch (Exception $e) {
            var_dump($e->getmessage());
            die();
        }

    }

    //扫码退款页面
    public function X_myRefundInfo()
    {
        try {
            global $_P, $_G;
            $fans = $this->checkuser();
            $uid = $fans['uid'];
            $themeid = $_P['themeid'];
            $_C = $config = Theme::getConfig($themeid);
            $theme = Theme::getThemeById($themeid);
            $system = $_G['system'];
            $fromuid = isset($_P['fromuid']) ? intval($_P['fromuid']) : 0;
            //查找员工信息
            $fromuserinfo = db_get(t_worker, ['uid' => $fromuid, 'themeid' => $themeid]);
            $url = $_G['siteroot'] . createMobileUrl('index', array("themeid" => $themeid, "soft" => $theme['softkey']));
            if (!$fromuserinfo) {
                return return_msg('未找到工作人员信息', $url, 'error');
            }
            if ($fromuid == $uid) {
                db_update(t_fans, ['ip' => $_G['clientip']], ['uid' => $_G['member']['uid'], 'themeid' => $themeid]);
                return return_msg('您的网络信息已同步', $url, 'success');
            }
            $themyrecord = Record::getAttendByThemeIdAndOpenid($themeid, $_G['openid'], false);
            if (empty($themyrecord)) {
                return return_msg('未查到您的付款定单', $url, 'error');
            }
            $themyorder = Order::getPayOrderByRIdZhifude($themyrecord['id']);

            $themyrecord['mobile'] = mb_substr($themyrecord['mobile'], 0, 3, 'utf-8') . '****' . mb_substr($themyrecord['mobile'], -4, 4, 'utf-8');

            $themyorder['realfee'] = sprintf("%.2f", $themyorder['realfee']);

            $result = array();

            $themyorder = $result['themyorder'] = $themyorder;
            $themyrecord = $result['themyrecord'] = $themyrecord;

            $return_clicent = get_defined_vars();
            return view('fcworker/fc_refund', $return_clicent);
        } catch (Exception $e) {
            var_dump($e->getmessage());
            die();
        }

    }

    public function RankSingle()
    {
        global $_P, $_G;
        $fans = $this->checkuser();
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $theme = Theme::getThemeById($themeid);
        $config = Theme::getConfig($themeid);
        if ($_P['isindex'] == 1) {
            if ($config['rank_order_new'] > 0) {
                $config['rank_order'] = $config['rank_order_new'];
                $config['rank_show'] = $config['rank_show_new'];
                $config['rank_user_type'] = $config['rank_user_type_new'];
                $config['rank_top_img'] = $config['rank_top_img_new'];
            }
        }
        $r = Record::getrank($system, $theme, $config, $themeid, true);


        if ($r['errcode'] == 1) {
            return return_msg($r['msg']);
        }
        $result = $r['data'];
        if (intval($_P['page']) <= 1) {
            $result['jishu'] = Worker::getjishu($theme, $system, $config['pinpailogo']);
            $return_clicent = get_defined_vars();
            return view('base/ranksingle', $return_clicent);
        } else {
            return return_msg($result, '', 'ajax');
        }
    }


    //员工扫客户码核销
    public function MyorderWorkerCheck()
    {
        global $_P, $_G;
        $from_type = isset($_P['from_type']) ? $_P['from_type'] : 1;
        $baseinfo = $this->Isworker();
        $config = $baseinfo['config'];
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $theme = Theme::getThemeById($themeid);
        $result = Worker::MyorderWorkerCheck($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        $url = $_G['siteroot'] . createMobileUrl('index', array("themeid" => $themeid, "soft" => $theme['softkey']));
        //判断开启多产品核销修改from_type
        if ($system['mulit_products'] == 1) {
            $from_type = 2;
        }
        if ($from_type == 1) {
            if ($result['error'] == 1) {
                die(Util::showError($result['msg']));
                return;
            } elseif ($result['tishi'] == 1) {
                return return_msg('成功核销', $url, 'success');
            } else {
                return return_msg($result['msg'], $url, 'error');
            }
        } elseif ($from_type == 2) {
            if ($result['error'] == 1) {
                die(Util::showError($result['msg']));
                return;
            } elseif ($result['tishi'] == 2) {
                return return_msg($result['msg'], $url, 'error');
                return;
            } else {
                if (isset($_P['verify_type']) && $_G['ispost']) {
                    return_json(0, $result);
                } else {
                    $order_id = intval($_P['order_id']);
                    $themeid = intval($_P['themeid']);
                    $system = $baseinfo['system'];
                    if ($system['is_multiple_merchants']) {
                        $shop_item = db_get(t_shangjia, ['id' => $baseinfo['myworker']['company']]);
                    }
                    $record_item = db_get(t_record, ['themeid' => $themeid, 'id' => $order_id]);
                    $return_clicent = get_defined_vars();
                    return view('base/dx_verify', $return_clicent);
                }

            }
        }

    }

    //清缓存
    public function clearsession()
    {
        global $_G, $_P;
        Session::clear();
        setcookie('user_sessionid', '', time() - 3600, '/');
        $url = urldecode($_P['old_url']);
        if (empty($url)) {
            $url = $_G['url_scheme'] . $_SERVER['HTTP_HOST'] . '/' . createMobileUrl('index', array('themeid' => intval($_P['themeid']), 'recrodid' => $_P['recrodid'], 'fromuid' => $_P['fromuid'], 'fopenid' => $_P['fopenid'], 'workerid' => $_P['workerid']));
        }
        if ($_P['auto'] == 'true') {
            echo "<script language='javascript' type='text/javascript'>";
            echo "window.location.href='$url';";
            echo "</script>";
            exit;
        } else {
            echo $_G['member']['uid'] . $_G['member']['nickname'];
            echo $_G['openid'];
            echo "<br><br>session_id:" . $_G['session_id'];
            echo $_COOKIE[session_name()];
            echo "<br><br>_SESSION:";
            var_dump($_COOKIE[session_name()]);
            $wait_time = 2;
            echo "<br><br>已清空客户端缓存";
            echo "<H2 id='page_div'>将在3秒后自动跳转首页</H2>";
        }
        echo "<meta content=\"width=device-width,user-scalable=no\" name=\"viewport\">";

        echo "<script language=\"javascript\">";
        echo "var num = '{$wait_time}'; ";
        echo "var id = window.setInterval('doUpdate()', 1000); ";
        echo "function doUpdate() {";
        if ($_P['auto'] != 'true') {
            echo "    document.getElementById('page_div').innerHTML = '将在'+num+'秒后自动跳转首页' ;";
        }
        echo "    if(num == 0) {";
        echo "        window.clearInterval(id);";
//        echo "        window.history.go(-1); ";
        echo "window.location.href='$url';";
        echo "    }";
        echo "    num --;";
        echo "}";
        echo "</script>";

    }

    public function NewGroup()
    {
        global $_P, $_G;
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $config = Theme::getConfig($themeid);
        $theme = Theme::getThemeById($themeid);
        $UserLevel = Theme::getUserLevel($_G['member']['uid'], $themeid);
        $url = $_G['siteroot'] . createMobileUrl('index', array("themeid" => $themeid, "fromuid" => $_G['member']['uid'], "soft" => $theme['softkey']));
        if ($config['newgroup'] == 1 && $UserLevel == 3 || $UserLevel == 4) {
            $themyrecord = Record::getRecordByUid($_G['member']['uid'], $themeid);
            $r = Record::newtuan($system, $themyrecord['id'], $themeid, $config);
            return return_msg('成功开新团', $url . "&fx=1&showtuan=1", 'success');
        } else {
            return return_msg('没有权限开新团', $url, 'error');
        }
    }

    //导出数据
    public function X_exportData()
    {
        global $_G, $_P;
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if ((stripos($user_agent, 'MicroMessenger') === false || empty($_G['openid']))) {
            $url = $_G['siteroot'] . createMobileUrl('index');

            if (!isset($_P['key']) || empty($_P['key'])) {
                return return_msg('参数错误', $url, 'error');
            }

            $key = $_P['key'];
            $themeid = intval($_P['themeid']);
            if (!$themeid) {
                return return_msg('参数错误1', $url, 'error');
            }

            $uid = intval($_P['uid']);
            if (!$uid) {
                return return_msg('参数错误2', $url, 'error');
            }

            $worker_info = db_find('SELECT id,status,level,download_auth,download_key,download_key_time FROM ' . tablename(t_worker) . '   WHERE themeid = :themeid AND uid = :uid', array(':themeid' => $themeid, ':uid' => $uid));
            if (empty($worker_info)) {
                return return_msg('数据不存在');
            }
            if ($worker_info['level'] != 1) {
                return return_msg('无权限导出', $url, 'error');
            }
            if ($worker_info['download_auth'] != 1) {
                return return_msg('无权限导出', $url, 'error');
            }
            if ($worker_info['download_key'] != $key) {
                return return_msg('验证失败', $url, 'error');
            }
            if ($worker_info['download_key_time'] < time()) {
                return return_msg('链接已过期，请重新从手机版后台进入');
            }

            $system = $_G['system'];
            $config = Theme::getConfig($themeid);
            $status = $_P['status'] ? $_P['status'] : -10;
            $type = isset($_P['type']) ? $_P['type'] : -1;;
            $yukuan = isset($_P['yukuan']) ? $_P['yukuan'] : 0;
            $workerid = isset($_P['workerid']) ? $_P['workerid'] : 0;

            $time = Record::getSearchTime();
            $starttime = $_P['starttime'] ? $_P['starttime'] : date('Y-m-d H:i:s', $time['starttime']);
            $endtime = $_P['endtime'] ? $_P['endtime'] : date('Y-m-d H:i:s', $time['endtime']);

            $nowoker = intval($_P['noworker']);

            //extract(Record::getSearchTime());
            extract(Recordbase::getCondition($system, $config, $themeid, $starttime, $endtime));

            $btn_info = Recordbase::btn($themeid, $system, $config, $_P, $condition);
            $range_btn = $btn_info['range_btn'];
            $status_btn = $btn_info['status_btn'];
            $yushou_btn = $btn_info['yushou_btn'];
            $tuan_num_info = $btn_info['tuan_num_info'];
            $options_btn = $btn_info['options_btn'];
            $formtwo_btn = $btn_info['formtwo_btn'];
            $address_btn = $btn_info['address_btn'];
            $wlist = $btn_info['wlist'];

            $tuannum = $_P['tuannum'];
            if (!$tuannum) {
                $tuannum = array();
            }
            unset($_P['fromuid']);
            $list = Recordbase::allList($themeid, $system, $config, $_P);
            extract($list);
            db_update(t_worker, ['download_key_time' => time() + 300], ['themeid' => $themeid, 'uid' => $_P['uid'], 'download_key' => $_P['key']]);
            $return_clicent = get_defined_vars();
            return view('fcworker/fc_export_data2', $return_clicent);
        } else {
            $fans = $this->checkuser();
            $themeid = intval($_P['themeid']);
            $uid = $_G['member']['uid'];
            $worker_info = db_find('SELECT id,status,level,download_auth,download_key,download_key_time FROM ' . tablename(t_worker) . '   WHERE themeid = :themeid AND uid = :uid', array(':themeid' => $themeid, ':uid' => $uid));
            if (empty($worker_info)) {
                return return_msg('数据不存在');
            }

            if ($worker_info['level'] != 1) {
                return return_msg('无权限导出');
            }

            if ($worker_info['download_auth'] != 1) {
                return return_msg('无权限导出');
            }

            if (!empty($_P['key']) && $_P['key'] == $worker_info['download_key'] && $worker_info['download_key_time'] > time()) {
                $download_url = $_G['siteroot'] . createMobileUrl('X_exportData', array('themeid' => $themeid, 'key' => $_P['key'], 'uid' => $_G['member']['uid']));
                $return_clicent = get_defined_vars();
                return view('fcworker/fc_export_data', $return_clicent);
            } else {
                $worker_item = db_get(t_worker, ['themeid' => $themeid, 'uid' => $uid]);
                $download_key1 = substr(md5($themeid . $worker_item['id'] . $worker_item['openid'] . $uid . time() . '@!download@data!#' . rand(1000, 9999)), 8, 16);
                $download_key2 = substr(md5($worker_item['openid'] . $worker_item['id'] . $themeid . $uid . time() . '@!download2@data2!#' . rand(1000, 9999)), 8, 16);
                $download_key = $download_key1 . $download_key2;
                $download_url = $_G['siteroot'] . createMobileUrl('X_exportData', array('themeid' => $themeid, 'key' => $download_key, 'uid' => $_G['member']['uid']));
                db_update(t_worker, ['download_key' => $download_key, 'download_key_time' => time() + 300], ['themeid' => $themeid, 'uid' => $uid]);
                echo "<script language='javascript' type='text/javascript'>";
                echo "window.location.href='$download_url';";
                echo "</script>";
                exit;
            }
        }
    }

    /**
     * Desc:分销管理
     * User:wyx
     * Time: 2023/9/6 17:38
     */
    public function X_fenxiao()
    {
        global $_P, $_G;
        $themeid = intval($_P['themeid']);
        $main = 'x_fenxiao';
        $op = isset($_P['op']) ? $_P['op'] : 'display';
        $baseinfo = $this->Isworker();
        $theme = Theme::getThemeById($themeid);
        $config = Theme::getConfig($themeid);
        $system = $baseinfo['system'];
        if ($op == 'display') {   //显示
            $result = Common::fxLists($themeid, $system, $config);
            $list = $result['list'];
            $page = $result['page'];
            $total = $result['total'];
            $hasNext = $result['hasNext'];
            if ($page == 1) {
                $btns = Common::btns($themeid, $system, $config);
                $return_clicent = get_defined_vars();
                return view('fcworker/fc_fenxiao', $return_clicent);
            } else {
                return_json(0, '', $result);
            }
        }
        //显示详情
        if ($op == 'info') {
            $info = Common::getInfo($themeid, $system);
            $res['data'] = $info['list'];
            $res['count'] = $info['total'];
            $res['msg'] = '';
            $res['code'] = 0;
            return json_encode($res);
        }
        //红包补发
        if ($op == 'check') {
            $id = $_P['id'];
            $result = Common::checkFee($id, $themeid, $system);
            return $result;
        }

    }


    /*
     *客服
     */
    public function X_client()
    {
        global $_G, $_P;
        $system = $_G['system'];
        $software = $_P['software'];
        if (!$software) {
            return_json(1, '活动编号不可为空');
        }
        $themeid = intval($_P['themeid']);
        if (!$themeid) {
            return_json(1, '活动ID不可为空');
        }
        $uid = intval($_P['uid']);
        if (!$uid) {
            return_json(1, '员工ID不可为空');
        }

        $worker_info = db_get($software . "_aworker", ['themeid' => $themeid, 'uid' => $uid]);

        if (!$worker_info) {
            return_json(1, '未找到工作人员信息', '');
        }

        if ($worker_info['level'] > 3) {
            return_json(1, '未找到工作人员信息', '');
        }

        //获取活动服务器编号
        $url = "https://oa.yixuan.net/app/index.php?i=2&c=entry&do=get_shop_name&m=yx99999&op=get_soft_info&softname={$software}";
        $res = file_get_contents($url);
        $res_array = json_decode($res, true);
        $res_data = $res_array['message'];
        if ($res_data['error'] == 0) {
            $url_data = $res_data['data'];
            $theme_url = $url_data['theme'];
            $record_url = $url_data['record'];
            $fans_url = $url_data['fans'];
            $comm_url = $url_data['comm'];
            $complate_url = $url_data['complate'];
            $daping_url = $url_data['daping'];
            $index_url = $url_data['index'];
            $addworker_url = $url_data['addworker'];
        }

        //显示订单信息
        switch ($worker_info['level']) {
            case 1:
                $level_name = '超级管理员';
                break;
            case 2:
                $level_name = '商家';
                break;
            case  3:
                $level_name = '员工';
                break;
        }

        $worker_where = '';
        $worker_where2 = '';
        if ($worker_info['level'] == 2) {
            $company = $worker_info['company'];
            $worker = db_getcolumn($software . "_aworker", array('company' => $company), 'uid');
            $worker_str = implode(',', $worker);
            $worker_where .= " AND workerid in ('$worker_str')";
            $worker_where2 .= " AND cm.workerid in ('$worker_str')";
        } else if ($worker_info['level'] == 3) {
            $worker_where .= ' AND workerid = {$uid}';
            $worker_where2 .= ' AND cm.workerid = {$uid}';
        }

        $day = date('Y-m-d', time());
        $head_sql = "SELECT  count(case when  status!=3  then 1 end) as all_num,
                               count(case when  from_unixtime(addtime,'%Y-%m-%d')='{$day}' and status!=3  then 1 end) as day_all_num,
                               count(case when  status > 0  and status!=3   then 1 end) as pay_num,
                               count(case when  from_unixtime(addtime,'%Y-%m-%d')='{$day}' and status > 0 and status!=3  then 1 end) as day_pay_num,
                               count(case when  status = -1   then 1 end) as refund_num,
                               count(case when  from_unixtime(addtime,'%Y-%m-%d')='{$day}' and status=-1  then 1 end) as day_refund_num,
                               count(case when  status=3 then 1 end) as offline_num,
                               count(case when  from_unixtime(addtime,'%Y-%m-%d')='{$day}' and status=3  then 1 end) as day_offline_num
                        FROM " . tablename($software . '_arecord') . " WHERE themeid = {$themeid} " . $worker_where;
        $head_data = db_find($head_sql);

        $day_sql = "SELECT riqi,
                           sum(newfans) as all_fans,
                           sum(record) as all_record,
                           sum(recordzx) as all_recordzx,
                           sum(recordxx) as all_recordxx,
                           sum(fee) as all_fee,
                           sum(scansum) as all_scansum,
                           sum(forward) as all_forward,
                           sum(comm) as all_comm
                         FROM " . tablename($software . '_aworkerreport') . " WHERE themeid = {$themeid} {$worker_where} GROUP BY riqi ORDER BY riqi desc LIMIT  3";
        $day_list = db_select($day_sql);
        //订单
        $order_sql = "SELECT id,uid,username,nickname,avatar,fee,type,status,tuannum,workerid  FROM " . tablename($software . '_arecord') . "
                        WHERE themeid = {$themeid} and status > -2 {$worker_where}  ORDER BY addtime desc limit 5";
        $order_list = db_select($order_sql);
        //红包
        $comm_data_sql = "SELECT  sum(fee) as all_fee,
                              sum(case when status=0  then fee else 0 end) as no_fee,
                              sum(case when status=1  then fee else 0 end) as fa_fee
                       FROM " . tablename($software . '_acomm') . " WHERE   themeid = {$themeid} {$worker_where}";
        $comm_data = db_find($comm_data_sql);

        $mode_type = $system['isCommPoints'] == 1 ? '积分' : '红包';
        $comm_type_name = [
            0 => '一级分销',
            2 => '二级分销',
            3 => '三级分销',
            4 => '转发' . $mode_type,
            5 => '阅读' . $mode_type,
            6 => '员工提成',
            7 => '摇一摇' . $mode_type,
            8 => '补余款',
            9 => '单买',
            10 => '进入链接',
            11 => '自已报名',
            12 => '代理提成',
            15 => '额外补发',
            16 => '团长红包',
            99 => '手工提现',
        ];

        $comm_status_name = [
            0 => '未发放',
            1 => '已发放',
            5 => '已锁定'
        ];

        $comm_sql = "SELECT cm.id,cm.themeid,cm.uid,cm.recordid,cm.workerid,cm.type,cm.status,cm.msg,cm.addtime,cm.fee,cm.ip,cm.city,
                            f.nickname,f.avatar,f.username as user ,f.mobile FROM " . tablename($software . '_acomm') . " as cm
                     left join " . tablename(t_fans) . " as f on f.openid = cm.openid and f.themeid = cm.themeid WHERE cm.themeid = {$themeid} {$worker_where2} order by cm.id desc LIMIT 5";

        $comm_list = db_select($comm_sql);
        foreach ($comm_list as $key => $val) {
            $comm_list[$key]['type_name'] = $comm_type_name[$val['type']];
            $comm_list[$key]['status_name'] = $comm_status_name[$val['status']];
        }
        //投诉
        $complain_data_sal = "SELECT  count(id) as all_num,
                                      count(case when  status=1  then 1 end) as not_num,
                                      count(case when  status=2  then 1 end) as being_num,
                                      count(case when  status=3  then 1 end) as finish_num
                            FROM " . tablename('000complain')
            . " WHERE  software = '{$software}' AND  themeid = {$themeid} {$worker_where}";
        $complain_data = db_find($complain_data_sal);

        $complain_sql = "SELECT *  FROM " . tablename('000complain') . " WHERE  software = '{$software}' AND  themeid = {$themeid} {$worker_where}   ORDER BY created_at desc limit 5";
        $complain_list = db_select($complain_sql);

        $return_clicent = get_defined_vars();
        return view('fcworker/fc_client', $return_clicent);
    }

    public function LlSmsCallback()
    {
        global $_P, $_G;
        $themeid = intval($_P['themeid']);
        $theme = Theme::getThemeById($themeid);
        $config = Theme::getConfig($themeid);
        $system = $_G['system'];
        $input = $_P['__input'];
        yxlog($input, '联麓回调');
        if ($input['codeDesc'] == '驳回' || $input['respCode'] == 'LLY:104') {
            $res = Sms::changeMarketing($system, $themeid, $input);
            return $res;
        } else {
            return '不是驳回';
        }
        return true;
    }

    public function Wx()
    {
        global $_G, $_P;
        $r = isset($_P['r']) ? trim($_P['r']) : '';
        if (!$r) {
            //r参数不存在提示模块不存在
            die('<H1>插件功能参数错误1:</H1>');
        }
        $route = new PluginRoute();
        $route->run(false);
    }

    //***********main方法调用************
    //直接调用MOD类里的main函数，可通过op执行不同的操作，解决h5与wxapp使用一套代码的问题；
    //调用说明：
    //----参数do:仅限main,参数mod为模块名，主函数名称必须是main
    //----可通过OP来控制调用哪个子函数
    //----参数isworker：true会验证只有员工才可以防问，若需验证需要在main函数二次验证是否为员工，防止更改isworker参数跳过验证；
    //返回数组说明：
    //----值error:0正常，1错误
    //----值msg:发生错误时的提示语
    //----值data:返回给前端的所有数据
    //----值data['page]:若此值不为空则加载对应模版页，若为空则JSON返回
    //----值jubf:当data['page]不为空加载模版页时，前端可直接用此值
    //----值jishu:当data['page]不为空加载模版页时，前端可直接用此值

    public function JumpPage()
    {
        global $_P, $_G;
        $fans = $this->checkuser();
        $return_clicent = get_defined_vars();
        return view('base/jumppage', $return_clicent);
    }

    public function Main()
    {
        global $_P, $_G;
        if (empty($_P['mod'])) {
            return return_msg('路径错误！');
        }
        extract($this->Isworker(!empty($_P['isworker'])));
        $result = Userdata::Main($system, $theme, $config, $fans, $themeid, $myworker);
        if ($result['error'] == 1) {
            if ($_G['ispost']) {
                return_json(1, $result['msg']);
            } else {
                return return_msg($result['msg']);
            }
        } else {
            if ($_G['ispost']) {
                return_json(0, '', $result['data']);
            } elseif ($_P['type'] == 1) {
                $sharedata = array(
                    'themeid' => $themeid,
                    'fopenid' => $_G['openid'],
                    'fromuid' => $_G['member']['uid'],
                );
                $workerurl = $_G['siteroot'] . createMobileUrl('index', $sharedata);
                //客户打开别人的链接，先转为自已的链接
                echo "<script language='javascript' type='text/javascript'>";
                echo "window.location.href='$workerurl';";
                echo "</script>";
                exit;
            } elseif (!empty($result['data']['page'])) {
                extract($result['data']);
                $return_clicent = get_defined_vars();
                return view($result['data']['page'], $return_clicent);
            }
        }
    }

}